I need to know if, using XPath in java, I can obtain a fragment of XML in result of a query. I'll explain better, I'm working oh this simple XML file:
<bookshelf>
<shelf>
<book>
<author>J.R.R. Tolkien</author>
<title>The Lord of the Rings</title>
</book>
</shelf>
</bookshelf>
The query XPath I have to evaluate is: /bookshelf/shelf/book
.
I need to find a way to keep the XML tag in the XPATH response getting a result like the following:
<author>J.R.R. Tolkien</author>
<title>The Lord of the Rings</title>
Is possible to do that?
Yes, that's possible using the standard java XPath API:
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Snippet {
public static void main(String[] args) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("/bookshelf/shelf/book/*",
new InputSource(Snippet.class.getResourceAsStream("/books.xml")),
XPathConstants.NODESET);
System.out.println("First node: " + nodes.item(0));
System.out.println("Second node: " + nodes.item(1));
}
}
You can ask the XPath API to return a list of nodes, a single node, a string, etc. Use the last argument to the evaluate
method for this: see XPathConstants
class.
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.