Search code examples
javaandroidxmlxpathsaxparser

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.


Solution

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