Stephen Sorensen
Stephen Sorensen

Reputation: 11945

xpath select referenced xml node

I need to select a node whose "name" attribute is equal to the current node's "references" attribute.

<node name="foo" />
<node name="bar" references="foo" />

I couldn't find a way to express this in XPATH. Any ideas. Ive tried the following:

./node[@name=@references]
./node[@name={@references}]

Obviously the above didn't work. I guess the real problem is in the brackets; how do I signify which attribute comes from which node?

Upvotes: 2

Views: 1024

Answers (3)

Tomalak
Tomalak

Reputation: 338326

The natural solution:

node[@name = current()/@references]

This works in XSLT, since you speak of "current node", which I translate as "the XSLT context node". No need for an extra variable.

Upvotes: 1

andre-r
andre-r

Reputation: 2705

I'm not entirely sure if this is what you want. This gives you any node which has references from any node to it:

//node[@name=//node/@references]

Upvotes: 3

James Sulak
James Sulak

Reputation: 32447

Unfortunately, what you're attempting isn't possible with pure XPath. Whenever you start a new predicate (the part surrounded by brackets), the context changes to the node that started the predicate. That means that you can't directly compare attributes from two separate elements in a single predicate without storing one in a variable.

What language are you using? You will have to store the value of the "name" attribute from the first node in a variable.

For example, in XSLT:

<xsl:variable name="name" select="/node[1]/@name" />
<xsl:value-of select="/node[@references = $name]" />

In XQuery

let $name := /node[1]/@name
return /node[@references = $name]

Upvotes: 2

Related Questions