I need to restrict the xpath node search to a subtree. I'm currently using the method below but it searches on a whole document regardlest whether I give it the document or the node I want to search from.
private NodeList findNodes(Object obj,String xPathString) throws ... {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile(xPathString);
return (NodeList) expression.evaluate(obj, XPathConstants.NODESET);
}
Solution I'm using now is that I create new document, append the node and search on the new document, then merge. I want to improve this. Can it be done?
The XPath I'm using is //nodeName
.
You're looking on the //
axis which means 'any descendant node of the document root',
Change it to .//
axis (descendands of the context node) and it will work as expected.
You need to distinguish between an absolute and relative XPath expression.
Good question +1.
In XPath, any expression that starts with /
is absolute XPath expression. An absolute XPath expression is evaluated on the complete current document.
By contrast, a relative XPath expression is evaluated off the current (context) node.
This explains the reported problem: //nodeName
is an absolute XPath expression.
What you want is a relative XPath expression, such as:
.//nodeName
.//nodeName
will search for a nodeName
element anywhere within the given context node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With