0

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 .

NilKha
  • 104
  • 3
  • 10

1 Answers1

0

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.

aglassman
  • 2,643
  • 1
  • 17
  • 30
  • I can't use /books/book/category because I will get 2 values and it will not be easy to identify 2nd category I got that is from book pqr or xyz. And if I am not wrong we can't use Xpath with SAX parser as per this post : [link here](https://stackoverflow.com/questions/8791600/can-sax-parsers-use-xpath-in-java) – NilKha Mar 02 '18 at 17:13
  • Why do you need to use XPath? If you already have it parsed as a document, you could also just use the Document API. – aglassman Mar 02 '18 at 17:25
  • it is just sample XML, I have lot of other XMLs and I am writing generic tool find all xml node values by specifing Xpath in configuration file. – NilKha Mar 07 '18 at 09:50