views:

87

answers:

2

Hi,

I am using xml and xqueries.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>

Thanks, Sony

+1  A: 

you use .. to get the parent, like this:

../childnode1

so if you have some xml document like this:

<a id="1">
  <b id="2">
    <c id="3">
      <d id="4"/>
    </c>
    <c id="5"/>
    <c id="6">
      <d id="7"/>
    </c>
  </b>
</a>

then the xquery

//../d[@id = "4"]

would return the c node with id of 3.

Nathan Hughes
@Nathan Hughes: Your expression means: *from all parents of decendant nodes (the same as all nodes having a child) a `d` child with `id` attribute equal to '4'*. So, it's not what the OP is asking...
Alejandro
A: 

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/..
Dimitre Novatchev