tags:

views:

177

answers:

3

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?

+2  A: 

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]
James Sulak
+2  A: 

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]
andre-r
True, I hadn't thought of that, if this is what you are going for.
James Sulak
This is extremely inefficient because of the nested `"//"` operator and should be avoided.
Tomalak
+1  A: 

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.

Tomalak