Reputation: 104
I am using javax.xml.xpath.XPath package to find nodes present in XML. Code finds values and return NodeList
NodeList nodes = (NodeList) xPath.compile("/books/book/category[1] | /books/book/category[2] | /books/book/category[3]").evaluate(xmlDocument,XPathConstants.NODESET);
And my sample XML is :
<books>
<book>
<name>abc</name>
<category>category1</category>
<isbn>152491915491444</isbn>
</book>
<book>
<name>pqr</name>
<isbn>1619126541625</isbn>
</book>
<book>
<name>xyz</name>
<category>category3</category>
<isbn>851926542599595</isbn>
</book>
</books>
I am getting 2 nodes in NodeList as 'category' is not present in 2nd node of XML.
So is there anyway to identify nodes I am getting from NodeList is result of which xpath I passed in xPath.compile? Because here it is not possible to identify value 'category3' is from node 2 or 3.
Or is there anyway to get node number in XML from which i got result. In this example I should get node 1 and 3 as the category i got is from 1st and 3rd nodes of XML .
Another approach is to pass single xpath instead of multiple xpaths. But I don't want to use this approach as it is time-consuming and I have to process a lot of such XMLs .
Upvotes: 0
Views: 149
Reputation: 2653
I have a few comments on this. First, I think you are using the wrong tool for the job depending on what your desired output is. Second is that XML 1.0 does not specify order of child elements. Most parsers will return elements in the order they are specified, but it could differ.
You can get the same results as above with the following xpath expression:
/books/book/category
The nodes in NodeList should be in the correct order. If you need to know what index these elements appear in, you'll need a different tool such as a SAX parser. With a Sax parser, you would be able to keep track of the number of book elements you have parsed, and therefore give them an index value.
Upvotes: 0