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

如何用XSLT对唯一员工的Maximum字段进行求和?

问题:对去重后的员工Maximum字段求和

给定以下XML数据:

<root>
   <row>
      <Leave_days>6</Leave_days>
      <Maximum>10</Maximum>
      <Employee>John</Employee>
   </row>
   <row>
      <Leave_days>4</Leave_days>
      <Maximum>15</Maximum>
      <Employee>Albert</Employee>
   </row>
   <row>
      <Leave_days>2</Leave_days>
      <Maximum>10</Maximum>
      <Employee>John</Employee>
   </row>
</root>

需求是对Maximum字段求和,但需排除重复员工的记录——每个员工仅保留一条记录参与计算,示例中正确结果为25(John的10 + Albert的15),期望输出:

<Root>
   <row>25</row>
</Root>

现有XSLT代码未实现去重逻辑:

<xsl:template match="root">
    <Root>            
        <row>
            <xsl:value-of select="sum(row/Maximum)"/>
         </row>          
    </Root>
</xsl:template>

解决方案

方案1:XSLT 2.0及以上版本(使用group-by)

利用<xsl:for-each-group>按员工姓名分组,再对每个分组的Maximum值(取每组第一条记录即可)求和:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="root">
        <Root>
            <row>
                <xsl:value-of select="sum(for $group in group-by(row, Employee) return $group/Maximum[1])"/>
            </row>
        </Root>
    </xsl:template>
</xsl:stylesheet>

方案2:XSLT 1.0版本(使用Muenchian分组)

XSLT 1.0不支持group-by,需用Muenchian分组实现去重:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 定义分组键:按Employee字段的值分组 -->
    <xsl:key name="empKey" match="row" use="Employee"/>

    <xsl:template match="root">
        <Root>
            <row>
                <!-- 筛选每个分组的第一条记录,对其Maximum求和 -->
                <xsl:value-of select="sum(row[generate-id() = generate-id(key('empKey', Employee)[1])]/Maximum)"/>
            </row>
        </Root>
    </xsl:template>
</xsl:stylesheet>

两种方案都能实现需求,根据你使用的XSLT版本选择即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:20:22