xpathxqueryzorba

How to access the ancestor node in the same XQuery?


<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


Solution

  • 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>