简体   繁体   中英

BaseX XQUERY selecting nodes with the value of a specific attribute

XML sample:


    <mondial>
        <continent id="f0_119" name="Europe"/>
        <continent id="f0_123" name="Asia"/>
        <continent id="f0_126" name="America"/>
        <continent id="f0_129" name="Australia/Oceania"/>
        <continent id="f0_132" name="Africa"/>
        <country id="f0_136" name="Albania" capital="f0_1461" population="3249136"
                 datacode="AL" total_area="28750" population_growth="1.34"
                 infant_mortality="49.2" gdp_agri="55" gdp_total="4100"
                 inflation="16" indep_date="28 11 1912"
                 government="emerging democracy" car_code="AL">
            <name>Albania</name>
            <city id="f0_1461" country="f0_136" longitude="10.7" latitude="46.2">
                <name>Tirane</name>
                <population year="87">192000</population>
            </city>
            <city id="f0_36498" country="f0_136" longitude="19.2" latitude="42.2">
                <name>Shkoder</name>
                <population year="87">62000</population>
                <located_at type="lake" water="f0_39058"/>
            </city>
        </country>
    </mondial>

for $x in //mondial/country/population
where $x/@year=87
return $x/name

I'm basically trying to return <name> from the node <population> that has the attribute of year=87 . I know it sounds confusing as heck, I can't even find documentation for this I've tried googling how to select using the attribute but I can't seem to return anything.

Please try the following XQuery.

XQuery

for $x in //mondial/country/city
where $x/population/@year=87
return $x/name

Please note that the population elements in your XML document are children of the city elements. Next, you tried to loop over the population elements, and it's better to move this path step into the where clause. One solution for returning the city names is as follows:

for $city in /mondial/country/city
where $city/population/@year = 87
return $city/name

You can get to the required information with a single XPath

//city[population/@year=87]/name

Live Demo (xqueryfiddle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM