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.