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

如何从XPath的map序列中获取去重值?解决distinct-values报错

Map序列去重的XPath原生解决方案

问题背景

需要对一组map序列执行去重操作,最初尝试使用fn:distinct-values()函数,代码如下:

<xsl:variable name="sequence" select="
              ( map { 'foo' : 1, 'bar' : () },
                map { 'foo' : 1, 'bar' : '3' },
                map { 'foo' : 1, 'bar' : '3' } )" as="map(xs:string,item()*)*"/>
<xsl:variable name="distinct" select="distinct-values($sequence)"/>

但触发FOTY0013错误,提示该函数要求参数为原子值,而map类型无法原子化。期望得到的去重结果为:

( map { 'foo' : 1, 'bar' : () },
  map { 'foo' : 1, 'bar' : '3' } )

已知可通过for-each-group或递归函数实现,但希望使用XPath原生工具,同时面临空序列作为map值的比较难题。

原生解决方案:使用fn:distinct()函数

在XPath 3.1及以上版本中,可直接使用fn:distinct()函数替代distinct-values(),该函数支持非原子值(包括map)的序列去重,默认采用值相等性规则比较map:

<xsl:variable name="sequence" select="
              ( map { 'foo' : 1, 'bar' : () },
                map { 'foo' : 1, 'bar' : '3' },
                map { 'foo' : 1, 'bar' : '3' } )" as="map(xs:string,item()*)*"/>
<xsl:variable name="distinct" select="distinct($sequence)"/>

原理说明

  • fn:distinct()不要求参数原子化,可直接处理map序列;
  • 对于map的比较,遵循XPath 3.1的map值相等规则:两个map当且仅当包含完全相同的键,且每个键对应的序列值都相等(包括空序列()的情况)时,判定为相等;
  • 该方法完全依赖XPath原生工具,无需额外分组或递归逻辑,简洁高效。

内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:40:07