You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对XPath统计生成的map按值降序排序并输出键?

基于统计生成的Map按值降序输出键

我用map统计elem节点attr属性各值的出现次数,示例XML如下:

<root>
    <elem attr="a"/>
    <elem attr="b"/>
    <elem attr="b"/>
    <elem         />
    <elem attr="a"/>
    <elem attr="c"/>
    <elem attr="b"/>
</root>

使用以下XQuery代码完成统计:

fold-left(
    //elem/@attr,
    map{},
    function($m,$a) {map:put($m, $a, sum((1, $m($a))))}
)

生成的统计Map为:

{
  "a": 2,
  "b": 3,
  "c": 1
}

现在需要基于这个Map,按整数值降序排序后输出对应的键,期望输出:

b
a
c

该如何实现?


实现方法

可以通过三步完成需求:将Map转为键值对序列、按值降序排序、提取并输出排序后的键,对应的XQuery代码如下:

let $count-map := fold-left(
    //elem/@attr,
    map{},
    function($m,$a) {map:put($m, $a, sum((1, $m($a))))}
)
return
string-join(
    for $entry in map:entries($count-map)
    order by $entry?value descending
    return $entry?key,
    '&#10;'
)

代码说明:

  • map:entries($count-map):把Map转换为键值对序列,每个项的结构为{"key": "属性值", "value": 出现次数}
  • order by $entry?value descending:根据值的大小降序排列键值对
  • return $entry?key:提取排序后的属性值键
  • string-join(..., '&#10;'):用换行符连接所有键,输出符合期望的逐行格式

如果不需要拼接成字符串,想直接逐行输出,也可以用简化的循环写法:

let $count-map := fold-left(
    //elem/@attr,
    map{},
    function($m,$a) {map:put($m, $a, sum((1, $m($a))))}
)
return
for $entry in map:entries($count-map)
order by $entry?value descending
return $entry?key

内容的提问来源于stack exchange,提问作者Fravadona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:15:32