Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch specific nodes from XML using XPath in Java?

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.

like image 491
Krish Avatar asked Jun 08 '15 05:06

Krish


People also ask

Can you use XPath expression used to select the target node and its values?

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.

How selecting XML data is possible with XPath explain?

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.


1 Answers

"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 id

You 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

like image 120
har07 Avatar answered Nov 15 '22 01:11

har07