I would like to check is code = "ABC" exists in my xml file using xPath.Can you please suggest me some methods for it?
<metadata>
<codes class = "class1">
<code code = "ABC">
<detail "blah blah"/>
</code>
</codes>
<codes class = "class2">
<code code = "123">
<detail "blah blah"/>
</code>
</codes>
</metadata>
[EDIT]
I did following. It reuturns null.
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//codes/code[@ code ='ABC']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: "+ nodes.item(i).getNodeValue());
}
I don’t know how you tested your code because
<detail "blah blah"/>is an incorrect xml construct it should be<detail x="blah blah"/>i.e. a name-value pair !!For the XPath Expression
"//codes/code[@ code ='ABC']"thenodes.item(i).getNodeValue())is going to benullbecause it will return an Element. See the below Javadoc comment:A working sample: