如何在XSLT 1.0中使用Muenchian分组实现多字段分组
解决方案
原代码问题说明
- 声明的XSLT版本为2.0,不符合XSLT 1.0的使用需求
- 分组键仅使用了第二个Cell的值,没有拼接第一、第二、第三个Cell作为联合分组依据
- 节点匹配路径和提供的示例XML结构不匹配,示例XML根节点直接是
DataSet,不存在外层的GenericBrowseResponse/Select/Response/Selection层级 - 分组选取逻辑错误,没有正确定位每个分组的首个
Row节点
正确实现代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <!-- 定义联合分组键,拼接前三个Cell的值作为分组依据,用|作为分隔符避免字段值拼接冲突 --> <xsl:key name="invoice-group" match="Row" use="concat(Cells/Cell[1], '|', Cells/Cell[2], '|', Cells/Cell[3])"/> <xsl:template match="/DataSet"> <DataSet> <!-- 选取每个分组的首个Row节点 --> <xsl:for-each select="Row[generate-id() = generate-id(key('invoice-group', concat(Cells/Cell[1], '|', Cells/Cell[2], '|', Cells/Cell[3]))[1])]"> <Invoice> <Key> <Company><xsl:value-of select="Cells/Cell[1]"/></Company> <Type><xsl:value-of select="Cells/Cell[2]"/></Type> <Num><xsl:value-of select="Cells/Cell[3]"/></Num> </Key> <Customers> <!-- 遍历当前分组下的所有Row,取第四个Cell作为客户编号 --> <xsl:for-each select="key('invoice-group', concat(Cells/Cell[1], '|', Cells/Cell[2], '|', Cells/Cell[3]))"> <Customer><xsl:value-of select="Cells/Cell[4]"/></Customer> </xsl:for-each> </Customers> </Invoice> </xsl:for-each> </DataSet> </xsl:template> </xsl:stylesheet>
实现说明
- 多列Muenchian分组的核心是将多个分组字段的值用不会出现在业务数据中的分隔符拼接为一个字符串,作为
xsl:key的use属性值 - 通过
generate-id()对比当前节点和对应分组首个节点的唯一ID,筛选出所有不重复的分组 - 遍历每个分组时,通过定义的key可以快速取出当前分组下的所有关联行,提取第四个Cell的值生成
Customer节点
内容的提问来源于stack exchange,提问作者Sunfile
相关产品推荐
相关产品推荐

