Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath search on subtree

Tags:

java

xml

xpath

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.

like image 502
Ondrej Sotolar Avatar asked Dec 02 '11 15:12

Ondrej Sotolar


3 Answers

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.

like image 155
soulcheck Avatar answered Nov 12 '22 21:11

soulcheck


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
like image 32
Dimitre Novatchev Avatar answered Nov 12 '22 20:11

Dimitre Novatchev


.//nodeName will search for a nodeName element anywhere within the given context node.

like image 3
Paul Butcher Avatar answered Nov 12 '22 22:11

Paul Butcher