java xml dom解析

发布于 2024-12-19 22:34:05 字数 3443 浏览 1 评论 0原文

我正在开发这个项目,我想解析一个如下所示的 xml 文件:

<?xml version='1.0' encoding='UTF-8'?>
<projectlist>
  <project>
    <name>SuperDuperApp</name>
    <type>batch</type>
    <prod>
      <server>testserver01</server>
    </prod>
    <qa>
      <server>testserver01</server>
    </qa>
    <dev>
      <server>testserver01</server>
    </dev>
  </project>
  <project>
    <name>Calculator</name>
    <type>deploy</type>
    <prod>
      <server>testserver02</server>
      <server>testserver03</server>
      <server>testserver04</server>
    </prod>
    <qa>
      <server>testserver05</server>
      <server>testserver06</server>
      <server>testserver07</server>
    </qa>
    <dev>
      <server>testserver12</server>
      <server>testserver13</server>
      <server>testserver14</server>
    </dev>
  </project>
</projectlist>

使用此方法解析文件并尝试以以下格式打印:

name: SuperDuperApp
type: batch
server: testserver01

name: Calculator
type: deploy
environment: dev
server: testserver12
server: testserver13
server: testserver14

etc.
public void parseXML() {
     ArrayList al = new ArrayList();
     HashSet hs = new HashSet();
    try {
        InputStream file = this.getClass().getResourceAsStream(
                "/net/swing/sandbox/util/config/projectlist.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();

        System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("project");

        System.out.println("Information of all servers...");

        for (int i=0;i<nList.getLength();i++){
            Node fstNode = nList.item(i);

            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElement = (Element) fstNode;

                NodeList nameElementList = fstElement.getElementsByTagName("name");
                Element nameElement = (Element) nameElementList.item(0);
                NodeList name = nameElement.getChildNodes();
                System.out.println("project name: " + ((Node) name.item(0)).getNodeValue());
                hs.add(((Node) name.item(0)).getNodeValue());

                NodeList typeElementList = fstElement.getElementsByTagName("type");
                Element typeElement = (Element) typeElementList.item(0);
                NodeList type = typeElement.getChildNodes();
                System.out.println("Deploy type: " + ((Node) type.item(0)).getNodeValue());

                //print out server list can't do it for some reason         
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


     try {
     al.clear();
     al.addAll(hs);
     Collections.sort(al);
     for (int z = 0; z < al.size(); z++) {
     listModel.addElement(al.get(z));
     }
     } catch (Exception e) {
     e.printStackTrace();
     }
     lstProject.validate();

}

所以我重写了我的方法,现在我陷入了困境 < ;---新人

I have this project I'm working on where I want to parse an xml file that looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<projectlist>
  <project>
    <name>SuperDuperApp</name>
    <type>batch</type>
    <prod>
      <server>testserver01</server>
    </prod>
    <qa>
      <server>testserver01</server>
    </qa>
    <dev>
      <server>testserver01</server>
    </dev>
  </project>
  <project>
    <name>Calculator</name>
    <type>deploy</type>
    <prod>
      <server>testserver02</server>
      <server>testserver03</server>
      <server>testserver04</server>
    </prod>
    <qa>
      <server>testserver05</server>
      <server>testserver06</server>
      <server>testserver07</server>
    </qa>
    <dev>
      <server>testserver12</server>
      <server>testserver13</server>
      <server>testserver14</server>
    </dev>
  </project>
</projectlist>

With this method parsing the file and trying to print out in the format:

name: SuperDuperApp
type: batch
server: testserver01

name: Calculator
type: deploy
environment: dev
server: testserver12
server: testserver13
server: testserver14

etc.
public void parseXML() {
     ArrayList al = new ArrayList();
     HashSet hs = new HashSet();
    try {
        InputStream file = this.getClass().getResourceAsStream(
                "/net/swing/sandbox/util/config/projectlist.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();

        System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("project");

        System.out.println("Information of all servers...");

        for (int i=0;i<nList.getLength();i++){
            Node fstNode = nList.item(i);

            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElement = (Element) fstNode;

                NodeList nameElementList = fstElement.getElementsByTagName("name");
                Element nameElement = (Element) nameElementList.item(0);
                NodeList name = nameElement.getChildNodes();
                System.out.println("project name: " + ((Node) name.item(0)).getNodeValue());
                hs.add(((Node) name.item(0)).getNodeValue());

                NodeList typeElementList = fstElement.getElementsByTagName("type");
                Element typeElement = (Element) typeElementList.item(0);
                NodeList type = typeElement.getChildNodes();
                System.out.println("Deploy type: " + ((Node) type.item(0)).getNodeValue());

                //print out server list can't do it for some reason         
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


     try {
     al.clear();
     al.addAll(hs);
     Collections.sort(al);
     for (int z = 0; z < al.size(); z++) {
     listModel.addElement(al.get(z));
     }
     } catch (Exception e) {
     e.printStackTrace();
     }
     lstProject.validate();

}

So I rewrote my method and now I'm just stuck <---newb

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

那小子欠揍 2024-12-26 22:34:06

查看 Node 的文档。每个节点都有一个方法 getChildNodes。检查子节点是否存在,然后像您所做的那样迭代它们。

Check the documentation for Node. Each node has a method getChildNodes. Check that for the existence of children nodes and than iterate over them like you are doing.

滥情哥ㄟ 2024-12-26 22:34:06

如果您的 xml 是使用 xsd 模式创建的,则可以使用 JAXB 为其创建类,并使用 xjc工具。这应该会让你的生活更轻松一些。

If your xml was created using an xsd schema, you could instead use JAXB to create classes for it, using the xjc tool. That should make your life a bit easier.

-柠檬树下少年和吉他 2024-12-26 22:34:06

我认为在您的情况下使用 XSLT 转换是合适的(更少的样板代码)请参阅 TransformerFactory 和用于 xml 处理的 java api。

I think it's appropriate to use XSLT transform in your case (much less boilerplate code) Look at TransformerFactory and java api for xml processing.

沙沙粒小 2024-12-26 22:34:06

作为问答解决方案,您可以应用与获取“项目”节点相同的策略:

...
System.out.println("servers:");

NodeList sList = eElement.getElementsByTagName("server");
for (int i = 0; i < sList.getLength(); i++) {
    String stuff = sList.item(i).getFirstChild().getNodeValue();
    System.out.println(stuff);
}

As a q&d solution you could apply the same strategy as for getting "project" node:

...
System.out.println("servers:");

NodeList sList = eElement.getElementsByTagName("server");
for (int i = 0; i < sList.getLength(); i++) {
    String stuff = sList.item(i).getFirstChild().getNodeValue();
    System.out.println(stuff);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文