我怎么知道哪个是 XML 中人口最多的城市?

How can I know which is the most populated city in this XML?

我有一个 XML 这样的:

<countries>
        <country name="Austria" population="8023244" area="83850">
            <city>
                <name>Vienna</name>
                <population>1583000</population>
            </city>
        </country>
        <country name="Spain" population="39181112" area="504750">
            <city>
                <name>Madrid</name>
                <population>3041101</population>
            </city>
        </country>
       [...]
</countries>

我需要一个 xQuery 表达式来获取人口最多的城市的名称,但我不知道该怎么做。一些想法?

你可以试试这个:

//city[population = max(/countries/country/city/population)]/name

嗯,select city 元素,select 最大人口,然后是拥有该人口的城市:

let $cities := //city,
      $max-pob := max($cities/population)
return $cities[population = $max-pob]/name

或者排序并取第一个:

(for $city in //city
order by $city/population descending
return $city)[1]/name

您还可以使用 sort 函数:

sort(//city, (), function($c) { xs:decimal($c/population) })[last()]/name

XQuery 1.0 中的传统方式是

let $p := max(//population) 
return //city[population = $p]/name

但这样做的缺点是要扫描两次数据。

您可以使用高阶函数来避免这种情况,例如 D4.6.1 (https://www.w3.org/TR/xpath-functions-31/#highest-lowest) 规范中作为示例显示的 eg:highest() 函数或折叠操作:

let $top := fold-left(//city, head(//city), 
    function($top, $this) {
      if (number($this/population) ge number($top/population)) 
      then $this else $top
    })
return $top/name

Saxon 提供了一个扩展函数saxon:highest,相当于规范中的eg:highest例子,所以你可以这样写

saxon:highest(//city, function($city){number($city/population)})/name