How to access the ancestor node in the same XQuery?

333 Views Asked by At
<results>
{
    for $p in
    (
    for $o in doc("mondial-3.0.xml") /mondial/organization
    where fn:count($o/members)
    order by fn:count($o/members) descending
    return <organization>
            <name> {$o/@name/string()} </name>
            <abbreviation> {$o/@abbrev/string()} </abbreviation>
            <num_members> {fn:count($o/members)} </num_members>
            <members> {for $m in doc("mondial-3.0.xml") $o/members
            return <country> {mondial/country[@id=$m/@country]/@name/string()} </country>} </members>
       </organization>
    )[position() < 10]
    return $p
}
</results>

I am unable to access the ancestor node in this problem as I have got an id stored of a parameter and now I want to match the id of that parameter and get a name of the parameter.

I am not getting any output for this. I am not sure where I am going wrong.

XML FILE :-

The link for the xml file is https://raw.githubusercontent.com/kroell/hsrm-mi-2semester-markuplanguage/master/Abgabe2/Aufgabe2/mondial-3.0.xml

2

There are 2 best solutions below

5
har07 On BEST ANSWER

In the link you posted, the root element of the XML is mondial not users, so I'd use mondial in this answer. Notice that member of organization and country are linked by country id, so you can do as follow to get country name of every member element :

<f> 
{
    for $m in $o/members
    return <g> {mondial/country[@id=$m/@country]/@name/string()} </g>
} 
</f>

Here is the complete working query. Tested in http://www.xpathtester.com/xquery using XML from the link posted in question as input :

<a>
{
    for $p in
    (
    for $o in /mondial/organization
    where fn:count($o/members)
    order by fn:count($o/members) descending
    return <b>
            <c> {$o/@name/string()} </c>
            <d> {$o/@abbrev/string()} </d>
            <e> {fn:count($o/members)} </e>
            <f> {for $m in $o/members
            return <g> {/mondial/country[@id=$m/@country]/@name/string()} </g>} </f>
       </b>

    )[position() < 10]
    return $p
}
</a>
2
Michael Kay On

You don't define the desired output of your query so it's hard to tell you why your query isn't giving the desired output; but there are several things about the query that suggest it's completely wrong.

Firstly, $o is always a single <mem> element, so fn:count($o) is always 1, so the use of this expression in the where and order by clauses cannot have any useful effect.

Secondly, the expression used to produce the content of the <f> element looks all wrong because it doesn't depend in any way on the value of $o.