如何在XSLT 1.0中遍历唯一记录并按员工ID汇总激励金?
解决方案:按部门分组汇总员工激励金XML转换
XSLT 1.0 实现(兼容多数处理器)
使用Muenchian分组机制,确保同一员工ID仅在所属部门内汇总:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- 定义分组键:拼接部门唯一标识与员工ID,避免跨部门合并 --> <xsl:key name="emp-by-id" match="Employee" use="concat(generate-id(../../Department), '|', Id)"/> <xsl:template match="/DepartmentData"> <root> <!-- 遍历每个部门 --> <xsl:for-each select="Department"> <Emps> <!-- 筛选当前部门下每个ID的首个Employee节点(分组依据) --> <xsl:for-each select="Employees/Employee[count(. | key('emp-by-id', concat(generate-id(../../Department), '|', Id))[1]) = 1]"> <Emp> <id><xsl:value-of select="Id"/></id> <!-- 汇总当前ID对应的所有激励金 --> <incentive> <xsl:value-of select="sum(key('emp-by-id', concat(generate-id(../../Department), '|', Id))/Incentive)"/> </incentive> </Emp> </xsl:for-each> </Emps> </xsl:for-each> </root> </xsl:template> </xsl:stylesheet>
XSLT 2.0+ 简化实现(更直观)
如果使用支持XSLT 2.0及以上的处理器(如Saxon),可以直接用for-each-group语法:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/DepartmentData"> <root> <!-- 遍历每个部门 --> <xsl:for-each select="Department"> <Emps> <!-- 按员工ID分组当前部门下的所有Employee --> <xsl:for-each-group select="Employees/Employee" group-by="Id"> <Emp> <id><xsl:value-of select="current-grouping-key()"/></id> <!-- 汇总当前分组的激励金总和 --> <incentive><xsl:value-of select="sum(current-group()/Incentive)"/></incentive> </Emp> </xsl:for-each-group> </Emps> </xsl:for-each> </root> </xsl:template> </xsl:stylesheet>
使用说明
将上述XSLT代码保存为.xsl文件,配合你的输入XML,通过XSLT处理器(如Saxon、Xalan,或在线XML转换工具)执行转换,即可得到预期的输出结果。
内容的提问来源于stack exchange,提问作者Ravi Ranjan
相关产品推荐
相关产品推荐

