0

我有一个这样的 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 表达式来获取人口最多的城市的名称,但我不知道该怎么做。一些想法?

4

3 回答 3

1

好吧,选择city元素,选择最大人口,然后选择拥有该人口的城市,例如:

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
于 2017-11-21T09:10:31.447 回答
1

XQuery 1.0 中的传统方式是

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

但这有扫描数据两次的缺点。

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

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
于 2017-11-21T09:28:44.323 回答
0

你可以试试这个:

//city[population = max(/countries/country/city/population)]/name
于 2017-11-21T09:08:45.330 回答