0

I am trying to read below XML in Java, but due to not symmetrical element in XML, not able to read - and also, How can I check if the node is available or not

This is the 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>`

And this is the code I am trying-

 try {    
     File inputFile = new File("c://test.xml");
     DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     Document doc = dBuilder.parse(inputFile);
     doc.getDocumentElement().normalize();

    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 Name : " + 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());
        }
    } 
  • What does *"not able to read"* mean? – Andreas Feb 18 '16 at 17:13
  • I mean, I am not able to read above xml in java – Vaibhav Jaiswal Feb 18 '16 at 18:07
  • I just ran your code on that XML, and it was read fine. Code of course failed with NPE on the `getElementsByTagName("json-counter").item(0).getTextContent()` since there's no `` element in the first ``, but that's different. XML was parsed without error. – Andreas Feb 18 '16 at 18:29
  • Actually, I am not able to read "JSON Property" in java- java.lang.NullPointerException: Cannot invoke method getTextContent() on null object – Vaibhav Jaiswal Feb 18 '16 at 18:41
  • Yes, as I said, you get **`NullPointerException`** when calling `getTextContent()`, because `item(0)` returns null when there are no elements of the given tag name. The XML is read fine by Java, you're just using `getElementsByTagName()` and the returned `NodeList` wrong. – Andreas Feb 18 '16 at 21:33

2 Answers2

0

How can I check if the node is available or not

getElementsByTagName() returns a NodeList, which has a getLength() method that will return 0 if element is not found.

It will also return a value greater than 1 for json-counter and json-property, so hard-coding item(0) is probably not what you should be doing.

Also, using getElementsByTagName() means that you're extracting the elements regardless of position, so if the mixed sequence of json-counter and json-property has meaning, you can't use getElementsByTagName().

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

You could try using the Xpath factory. You can easily cast the Node to an Element.

import javax.xml.xpath.XPathFactory;
.
.
.
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = xpath.evaluate("/root/el1/el2[@attr='123']", yourDocOrNode, XPathConstants.NODE);

xpath.evaluate will either throw a XPathExpressionException, if the expression is not valid, or will return null if the element cannot be found.

DAB
  • 1,631
  • 19
  • 25