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

如何用XSLT或XPath统计重复值(仅计重复项各一次,结果为3)

XSLT/XPath统计重复项唯一计数的解决方案

要统计出现次数≥2的唯一名字数量(即你需要的结果3),可以通过以下两种方式实现:

方法1:使用for-each-group(推荐,性能更优)

利用分组功能先按名字分组,再筛选出重复的组并计数:

<xsl:variable name="MyValues" select="tokenize('~Kelly Watson~Andrew Lee~Andrew Lee~Susan Smith~Susan Smith~Susan Smith~Derin Gill~Derin Gill~William Jones', '~')"/>

<!-- 过滤tokenize生成的空字符串(原字符串开头的~导致的) -->
<xsl:variable name="non-empty-values" select="$MyValues[. != '']"/>

<!-- 统计出现次数≥2的唯一值数量 -->
<xsl:variable name="DuplicateCnt" select="count(for-each-group($non-empty-values, .)[count(current-group()) > 1])"/>

<!-- 输出结果,会返回3 -->
<xsl:value-of select="$DuplicateCnt"/>

步骤说明:

  1. $non-empty-values 排除了tokenize产生的第一个空元素,避免干扰统计
  2. for-each-group($non-empty-values, .) 按名字分组,每个组包含所有相同的名字条目
  3. [count(current-group()) > 1] 筛选出出现次数超过1次的组
  4. count(...) 统计符合条件的组数量,即为目标结果

方法2:纯XPath表达式实现

如果不想使用分组,也可以通过distinct-values和index-of组合实现:

<xsl:variable name="MyValues" select="tokenize('~Kelly Watson~Andrew Lee~Andrew Lee~Susan Smith~Susan Smith~Susan Smith~Derin Gill~Derin Gill~William Jones', '~')"/>

<!-- 直接计算重复项的唯一计数 -->
<xsl:variable name="DuplicateCnt" select="count(distinct-values($MyValues[. != ''])[count(index-of($MyValues, .)) > 1])"/>

<xsl:value-of select="$DuplicateCnt"/>

步骤说明:

  1. distinct-values($MyValues[. != '']) 获取所有非空的唯一名字列表
  2. [count(index-of($MyValues, .)) > 1] 筛选出在原列表中出现次数≥2的名字
  3. count(...) 统计这些名字的数量,得到结果3

两种方法都能返回你需要的计数3,其中for-each-group在数据量较大时性能更优,因为index-of需要多次遍历原列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:25:17