for-each-group_2-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_2-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:sort
select="@country"/>
<xsl:comment>
<xsl:value-of
select="current-grouping-key()"/>
</xsl:comment>
<xsl:for-each
select="current-group()">
<xsl:sort
select="@stock" data-type="number" order="descending"/>
<xsl:copy-of
select="."/>
</xsl:for-each>
</xsl:for-each-group>
</products>
</xsl:template>
</xsl:stylesheet>
for-each-group_2-output.xml
<?xml version="1.0" ?>
<products>
<!--Australia-->
<product
id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
<!--Denmark-->
<product
id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
<!--Germany-->
<product
id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
<product
id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
<!--Japan-->
<product
id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
</products>
First we sort the products to get "Australia" first, and inside each group we sort to get the product with highest stock first.
Updated 2009-03-19