My xml file structure is like this
<?xml version="1.0" encoding="utf-8" ?>
<book>
<chapters>
<chapter id="1">
<page id="1" cid= "1" bid = "Book1">
<text>Hi</text>
</page>
<page id="2" cid= "1" bid = "Book1">
<text>Hi</text>
</page>
</chapter>
<chapter id="2">
<page id="1" cid= "2" bid = "Book1">
<text>Hi</text>
</page>
<page id="2" cid= "2" bid = "Book1">
<text>Hi</text>
</page>
</chapter>
<chapter id="3">
<page id="1" cid= "3" bid = "Book1">
<text>Hi</text>
</page>
<page id="2" cid= "3" bid = "Book1">
<text>Hi</text>
</page>
</chapter>
</chapters>
</book>
I want to get the specific page node by passing page id, and chapter id. How can I achieve this ?
Also, the book node contains too many chapter and each chapter contains many pages. So, I am using SAX parser to parse the content.
XPath assertion uses XPath expression to select the target node and its values. It compares the result of an XPath expression to an expected value. XPath is an XML query language for selecting nodes from an XML. Step 1 − After clicking Add Assertion, select Assertion Category – Property Content.
XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.
"How can I fetch specific nodes from XML using XPath in Java?"
I'm not very familiar with Java and Android, but the xpath to get specific page
from your XML sample, passing page id
and chapter id
should look about like this :
//chapter[@id='chapter_id_here']/page[@id='page_id_here']
brief explanation :
//chapter
: find chapter
element anywhere in the XML...[@id='chapter_id_here']
: ...where id
attribute value equals specific chapter id/page
: from each of filtered chapter
elements, find child element page
...[@id='page_id_here']
: ...where id
attribute value equals specific page idYou can follow these threads for implementation to execute xpath expression in Java : How to read XML using XPath in Java, and in Android : Search in XML File with XPath in Android
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With