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

如何在XSLT转换文件中添加重复记录Row Count计数功能?

给重复的Employee ID+SSN记录添加Row Count序号(XSLT转CSV)

完全可以在现有XSLT代码里实现这个需求,核心是通过XSLT的节点统计或分组功能,为每组重复的Employee ID+SSN记录生成递增序号。以下是针对不同XSLT版本的具体修改方案:

假设你的源XML结构示例

<Employees>
  <Employee>
    <EmployeeID>123</EmployeeID>
    <SSN>111-22-3333</SSN>
  </Employee>
  <Employee>
    <EmployeeID>123</EmployeeID>
    <SSN>111-22-3333</SSN>
  </Employee>
  <Employee>
    <EmployeeID>456</EmployeeID>
    <SSN>444-55-6666</SSN>
  </Employee>
  <Employee>
    <EmployeeID>123</EmployeeID>
    <SSN>111-22-3333</SSN>
  </Employee>
</Employees>

方案1:XSLT 1.0 兼容版(适合旧环境)

如果你的XSLT处理器只支持1.0版本,修改现有代码如下:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <!-- 更新表头,新增Row Count列 -->
    <xsl:text>Employee ID,SSN,Row Count&#10;</xsl:text>
    <xsl:apply-templates select="Employees/Employee"/>
  </xsl:template>

  <xsl:template match="Employee">
    <!-- 生成唯一组键:拼接EmployeeID和SSN,用|分隔避免冲突 -->
    <xsl:variable name="groupKey" select="concat(EmployeeID, '|', SSN)"/>
    <!-- 统计当前节点之前同组的记录数,加1得到当前序号 -->
    <xsl:variable name="rowNum" select="count(preceding-sibling::Employee[concat(EmployeeID, '|', SSN) = $groupKey]) + 1"/>

    <!-- 输出三列内容 -->
    <xsl:value-of select="EmployeeID"/>,<xsl:value-of select="SSN"/>,<xsl:value-of select="$rowNum"/><xsl:text>&#10;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

方案2:XSLT 2.0+ 高效版(推荐)

如果你的处理器支持XSLT 2.0及以上(比如Saxon),用分组功能更高效,尤其适合大数据量:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <xsl:text>Employee ID,SSN,Row Count&#10;</xsl:text>
    <!-- 按EmployeeID+SSN组合分组 -->
    <xsl:for-each-group select="Employees/Employee" group-by="concat(EmployeeID, '|', SSN)">
      <!-- 遍历组内每条记录,用position()直接获取序号 -->
      <xsl:for-each select="current-group()">
        <xsl:value-of select="EmployeeID"/>,<xsl:value-of select="SSN"/>,<xsl:value-of select="position()"/><xsl:text>&#10;</xsl:text>
      </xsl:for-each>
    </xsl:for-each-group>
  </xsl:template>
</xsl:stylesheet>

输出效果示例

运行后会得到如下CSV内容:

Employee ID,SSN,Row Count
123,111-22-3333,1
123,111-22-3333,2
456,444-55-6666,1
123,111-22-3333,3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:15:33