Question

I need guidance in STAX java I have xml file, I need to get the inner element value prior satisfying previous parent node book id attribute value. For example.

<books>
<book id = "1">
   <chap num ="1"> This First Title </chap>
   <chap num ="2"> This second of first book </chap>
</book>
<book id = "2">
   <chap num ="1"> This First Title of second book </chap>
   <chap num = "2"> This Second of second book </chap>
</book>
</books>

I need the values of attribute from "chap" element based on comparing on of the book attribute id.

Just hint would guide me.

Was it helpful?

Solution

You would need to do something along these lines

String xmlString = ...
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlString);

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
String xpathExp = "/books/book[@id=\"2\"]";
Node node = (Node) xpath.evaluate(xpathExp, doc, XPathConstants.NODE);

From the "book" node, you can loop over the children ("chap" nodes). Or you can access the list of child nodes directly by:

String xpathExp = "/books/book[@id=\"2\"]/chap";
NodeList chapNodeList = (NodeList) xpath.evaluate(xpathExp, doc, XPathConstants.NODESET);

You can then retrieve the attribute values from the "chap" nodes. (example, node.getTextContent();)

Or if you know which chapter you want, modify the xpath expression to be more specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top