读取XML的子节点时错误 - 节点的第3级 - Java

时间:2016-02-18 13:03:18

标签: java xml path

我试图在JAVA中阅读以下XML -

这是我正在尝试的代码 -     `尝试{
         文件inputFile = new File(" c://test.xml");          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();          Document doc = dBuilder.parse(inputFile);          doc.getDocumentElement()正常化();

    NodeList nListNodePath = doc.getElementsByTagName("node-path");

     for (int i = 0; i < nListNodePath.getLength(); i++) {
        Node nNodePath = nListNodePath.item(i);
        if (nNodePath.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement1 = (Element) nNodePath;
    System.out.println("Node Path--- : "+eElement1.getAttribute("path"));
    System.out.println("Property:"+eElement1.getElementsByTagName("property-name").item(0).getTextContent());
            System.out.println("Property value : " + eElement1.getElementsByTagName("property-value").item(0).getTextContent());
            System.out.println("Json Counter : " + eElement1.getElementsByTagName("json-counter").item(0).getTextContent());
            System.out.println("JSON property : " + eElement1.getElementsByTagName("json-property").item(0).getTextContent());
        }
} 

这是XML -

`<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <node-path path="USA">
      <property-name>Name</property-name>
      <property-value><![CDATA[Cat A]]></property-value>
       </node-path>
   <node-path path="Canada">
      <property-name>Name</property-name>
      <property-value />
   </node-path>
   <node-path path="Australia">
      <property-name>Name</property-name>
      <json-counter>1</json-counter>
      <json-property><![CDATA[Cat A]]></json-property>
      <json-property><![CDATA[Cat B]]></json-property>
      <json-property><![CDATA[Cat C]]></json-property>
      <json-counter>2</json-counter>
      <json-property><![CDATA[Cat D]]></json-property>
      <json-property><![CDATA[Cat E]]></json-property>
      <json-property><![CDATA[Cat F]]></json-property>
      <property-value />
   </node-path>
   <node-path path="UK">
      <property-name>Name</property-name>
      <property-value><![CDATA[0]]></property-value>
   </node-path>
</Root>`

0 个答案:

没有答案