I have some trouble with XPath. For some unknown reason the result I get from my expression is the one from another run of the function.
Here’s the constructor of my class:
Wine(Node ndWine){
try{
xpath = XPathFactory.newInstance().newXPath();
}
catch(Exception e)
{}
Node ndName = null;
try{
ndName = (Node)xpath.evaluate("//name", ndWine, XPathConstants.NODE);
}
catch(Exception e)
{}
if (ndName != null)
name = ndName.getTextContent();
}
And here’s the XML:
<cellar>
<wine>
<name>Jasnières</name>
</wine>
<wine>
<name>Ballet d'Octobre</name>
</wine>
</cellar>
In the calling method I have another xpath expression that breaks down the document to the list of <wine> elements. The above code is called for each node.
In the debugger I check that on the second run the ndWine node actually contains data from the second node of the document, but the evaluation always returns the Jasnieres value instead of ballet d'octobre, which I can’t understand.
Any idea of the root cause?
Starting the XPath expression with
//makes it an absolute path. Even though you pass in the<wine>element it ignores it and starts at the document root. Add a.in front to make it a relative path:Or better yet, avoid the
//syntax if you can. It’s best to avoid doing a fulldescendant-or-selfsearch if you know exactly where the<name>elements will be. If they’ll always be directly inside of a<wine>element then use this XPath: