How to retrieve parent node using XQuery? How to retrieve parent node using XQuery? xml xml

How to retrieve parent node using XQuery?


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


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.


Here is a more complex example of getting the parent node (..).

Q) Find all situations where one country's most popular language is another country's least popular, and both countries list more than one language.https://prod-c2g.s3.amazonaws.com/db/Winter2013/files/countries.xml

A)

for $b in doc("countries.xml")/countries/country/languagefor $c in doc("countries.xml")/countries/country/languagewhere $b/../@name != $c/../@name and data($b) = data($c)and count($b/../language) > 1and count($c/../language) > 1and $b/@percentage = max($b/../language/@percentage)and $c/@percentage = min($c/../language/@percentage)return   <LangPair language="{data($b)}">     <MostPopular>{data($b/../@name)}</MostPopular>     <LeastPopular>{data($c/../@name)}</LeastPopular>    </LangPair>