<...">

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

My xml file structure looks 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 a specific node page by passing the page id and id head . How can i achieve this?

In addition, the node book contains too many chapters, and each chapter contains many pages. So, I use the SAX parser to parse the content.

+6
source share
1 answer

"How to get specific nodes from XML using XPath in Java?"

I am not very familiar with Java and Android, but xpath, to get a specific page from your XML example, passing the page id and chapter id should look something like this:

 //chapter[@id='chapter_id_here']/page[@id='page_id_here'] 

brief explanation:

  • //chapter : find the chapter element anywhere in the XML ...
  • [@id='chapter_id_here'] : ... where id is the attribute value equal to the specific id of the chapter
  • /page : from each of the filtered chapter elements, find the child page ...
  • [@id='page_id_here'] : ... where id is the attribute value equal to the specific page identifier

You can follow these threads for implementation to execute xpath expressions in Java: How to read XML using XPath in Java and Android: Search XML file with XPath in Android

+3
source

Source: https://habr.com/ru/post/988689/


All Articles