如果它是 XSLT 2.0,那么您可以使用嵌套<xsl:for-each-group>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<Groups>
<xsl:for-each-group select="/Groups/GroupData" group-by="@ID">
<xsl:for-each-group select="current-group()" group-by="if(@Key) then @Key else 'no key'">
<GroupData>
<!-- Copy attributes off the *first* GroupData element in the group -->
<xsl:copy-of select="current-group()[1]/@*"/>
<!-- Copy ItemData children from *all* GroupData elements in the group -->
<xsl:copy-of select="current-group()/ItemData" />
</GroupData>
</xsl:for-each-group>
</xsl:for-each-group>
</Groups>
</xsl:template>
</xsl:stylesheet>
(我假设您的输入文件有一个根元素<Groups>
并且不使用命名空间)。
如果是 XSLT 1.0,那么您需要使用Muenchian Grouping:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="group-data" match="GroupData" use="concat(@ID, '___', @Key)" />
<xsl:template match="/">
<Groups>
<!--
Iterate over a node set containing just one GroupData element for
each combination of ID and Key
-->
<xsl:for-each select="/Groups/GroupData[count( . | key('group-data', concat(@ID, '___', @Key))[1]) = 1]">
<GroupData>
<!-- Copy attributes from the "prototype" GroupData -->
<xsl:copy-of select="@*"/>
<!--
Copy ItemData children from *all* GroupData elements with matching
ID/Key
-->
<xsl:copy-of select="key('group-data', concat(@ID, '___', @Key))/ItemData" />
</GroupData>
</xsl:for-each>
</Groups>
</xsl:template>
</xsl:stylesheet>
在这里,我通过创建key
.{ID}___{Key}