for-each-group_1-input.xml
<?xml version="1.0"?>
<products>
<product
id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
<product
id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
<product
id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
<product
id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
<product
id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
</products>
for-each-group_1-stylesheet.xsl
<?xml version="1.0"?>
<xsl:stylesheet
version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output
indent="yes"/>
<xsl:template
match="/">
<products>
<xsl:for-each-group
select="products/product" group-by="@country">
<xsl:comment>
<xsl:value-of
select="current-grouping-key()"/>
</xsl:comment>
<xsl:for-each
select="current-group()">
<xsl:copy-of
select="."/>
</xsl:for-each>
</xsl:for-each-group>
</products>
</xsl:template>
</xsl:stylesheet>
for-each-group_1-output.xml
<?xml version="1.0" encoding="UTF-8"?>
<products>
<!--Denmark-->
<product
id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
<!--Germany-->
<product
id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
<product
id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
<!--Australia-->
<product
id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
<!--Japan-->
<product
id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
</products>
Note that the functions, current-grouping-key() and current-group(), are only awailable inside an xsl:for-each-group. We need an xsl:for-each inside xsl:for-each-group to handle all the items in the group.
Updated 2009-03-19