Could someone please explain why this is happening; this following is the code I’ve got:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
" <comment id=\"comment1\">\n" +
" <data> abcd </data>\n" +
" <data> efgh </data>\n" +
" </comment>\n" +
" <comment id=\"comment2\">\n" +
" <data> ijkl </data>\n" +
" <data> mnop </data>\n" +
" <data> qrst </data>\n" +
" </comment>\n" +
"</title>\n";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
NodeList nlist = doc.getElementsByTagName("comment");
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
NodeList nodes = (NodeList)xp.evaluate("//@*", nlist.item(0), XPathConstants.NODESET);
for(int i = 0; i < nodes.getLength(); i++)
System.out.println(nodes.item(i));
The output produced is:
text="title1"
id="comment1"
id="comment2"
The problem is, I am trying to do an XPath query on a sub-tree (i.e. the first comment block), so I just want to get all attributes for this sub-tree but for some reason, whichever sub-tree I pass in, it always returns all attribute nodes, as if the object being passed into the xpath evaluator is the root node.
How can I just pass in and evaluate all attributes for a subtree?
You have to omit the // from the XPath expression.