简体   繁体   中英

Returning the whole xml chunk from xml file Java XPath

I have been trying to figure out this solution online. I am finding out the most efficient way of parsing an XML file.

The following is my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<game>
    <person>
       <name>ABC</name>
       <address>XYZ</address>
       <age>35</age>
    </person>
    <place>
       <country>US</country>
       <state>California</state>
       <city>Fremont</city>
    </place>
    <thing>
       <name>Book</name>
       <use>Read and write</use>
    </thing>
</game>

I have to parse this XML file using xPath in Java. I would like to have /*[i] as the xPath expression where i is an integer and 0<i<4 . Also I would like to display the whole "chunk" of XML. That is if i=1, then the expression has to return <country>US</country><state>California</state><city>Fremont</city> . Please help me out with this.Please do NOT use DOM (Ex. Node class) for this in any of the steps of your solution. Also please try to use Apache Commons framework as it uses SAX Parser internally.

Thanks.

This is your appropriate xpath:

/game/child::*[position() = $i]

Supposing $i referring to value of variable i

  • Note that $i starting from 1

You can use jaxp xpath to implement that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM