简体   繁体   English

用Java解析xml文件

[英]parse xml file in java

i want to parse xml file in java. 我想解析java中的xml文件。 my code is this. 我的代码是这样的。 but when run it wrong data appear in console. 但是运行时,错误的数据会显示在控制台中。 my xml file such as this 我的xml文件是这样的

    <set>
   <employe>
     <name>reza</name>
     <id>1</id>>
    </employe> 
   <employee>
      <name>ali</name>
      <id>2</id>
   </employee>
    </set>

and my code is this: 我的代码是这样的:

 DocumentBuilderFactory factory = DocumentBuilderFactory
                            .newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 Document document = builder.parse(file.toFile());
 Element root = document.getDocumentElement();
 if (!root.hasChildNodes()) {
    paths.add(file);
 } else {
   System.out.println("Element Name in: "+file.getFileName());
   System.out.println("Root element: "
                       + "Total count: " + root.getChildNodes().getLength());
   for (int i = 0; i < root.getChildNodes().getLength(); i++) {
        Node node = root.getChildNodes().item(i);
        if (node.getChildNodes().getLength() != 0) {
            System.out.println("name: "+ node.getNodeName() + " size:"
                               + node.getChildNodes().getLength());
           }
         }
      }

and in console this data display 并在控制台中显示此数据

 Element Name in: file.xml
 Root element: Total count: 5
 name: employe size:5
 name: employee size:5

what is my problem? 我怎么了

您可能需要确保所获取的节点属于元素类型,否则,空格的计数方法与元素相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM