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

1

6

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.

Bonefish answered 8/6, 2015 at 5:39 Comment(5)
No xpath support in SAX? : Can SAX Parsers use XPath in Java?Suckow
I don't believe you can query using xpath with SAX because the document isn't fully held in memory at any time. You can of course store a list of chapters and pages in some data structure while parsing. Can you post your SAX related code?Bartlet
@Suckow Thanks for your update. I will use DOM Parser. Could you please provide me solution using DOM ?Bonefish
@Bartlet Thanks for your update. I will use DOM Parser. Could you please provide me solution using DOM ?Bonefish
Thanks for your update @BonefishVickeyvicki
S
3

"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

Suckow answered 8/6, 2015 at 6:19 Comment(2)
How can I specify multiple filters for page? Is the below format correct ?? //page[@id='2'&&@cid='1'&&bid='Book 1']Bonefish
&& operator in xpath is and : //page[@id='2' and @cid='1' and @bid='Book 1']Suckow

© 2022 - 2024 — McMap. All rights reserved.