How to retrieve parent node using XQuery?

sony picture sony · Sep 14, 2010 · Viewed 22.6k times · Source

I am using XML and XQuerie. I usually use an XPath expression relative to a parent node to retrieve its child node. But, I am not sure how to do the opposite meaning if I have a child node, how do I retrieve its parent node.

<node id="50>
  <childnode1 childid="51" />
  <childnode2 childid="52" />
</node>

If I have the node <childnode1 childid="51" />, how do I retrieve its parent: <node id="50>

Answer

Dimitre Novatchev picture Dimitre Novatchev · Sep 14, 2010

Short answer:

..

This selects the parent of the current (context) node.

Longer and more general answers:

//node()[childnode1/@childid="51"]

This selects any node in the document that has a child element named childnode1, that has an attibute childid, whose value is '51'.

One should try to avoid an expression that contains the // abbreviation, because this may be very inefficient. Use '//' only when the structure of the XML document isn't known in advance.

Best answer:

ExpressionSelectingTheChildNode/..