James Hutchison
James Hutchison

Reputation: 63

XPath Predicate - Access the origin node from selectSingleNode

I would like to know if there is a way to obtain the value of the origin node when doing a query.

I have an XPath query using selectSingleNode. I would like to be able to create a predicate where the test is against a value from the node being searched.

For example...

node.selectSingleNode("//node1/node2[anotherNode=origin()/originNode]/theReturningNode")

The origin() in this case is the node used in the selectSingleNode

Many Thanks

Upvotes: 0

Views: 99

Answers (2)

Michael Kay
Michael Kay

Reputation: 163595

If you install an XPath processor such as Saxon that implements an up-to-date version of XPath, then you can use the query

let $origin := . return
    //node1/node2[anotherNode=$origin/originNode]/theReturningNode

In fact some XPath 1.0 processors will allow you to run the query

//node1/node2[anotherNode=$origin/originNode]/theReturningNode

supplying the value of $origin as an external parameter via API.

You probably won't be able to use the DOM's selectSingleNode method, but other APIs are available (e.g. JAXP).

Upvotes: 1

Tomalak
Tomalak

Reputation: 338386

There is such a thing in XSLT (called current()), but it does not exist in XPath.

You have to build your XPath expression dynamically in this case:

"//node1/node2[anotherNode = '" + originNode.text + "']/theReturningNode"

Beware that this will produce invalid XPath (and therefore run-time errors) when originNode.text contains single quotes. This can be worked around if necessary. Different work-arounds apply to XPath 1.0 and 2.0.

Upvotes: 2

Related Questions