xsl:for-each-group (1)

  1. for-each-group_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
  5.   <product id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
  6.   <product id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
  7.   <product id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
  8.   <product id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
  9. </products>
  1. for-each-group_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="/">
  6.     <products>
  7.       <xsl:for-each-group select="products/product" group-by="@country">
  8.         <xsl:comment>
  9.           <xsl:value-of select="current-grouping-key()"/>
  10.         </xsl:comment>
  11.         <xsl:for-each select="current-group()">
  12.           <xsl:copy-of select="."/>
  13.         </xsl:for-each>
  14.       </xsl:for-each-group>
  15.     </products>
  16.   </xsl:template>
  17. </xsl:stylesheet>
  1. for-each-group_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <products>
  4. <!--Denmark-->
  5.   <product id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
  6. <!--Germany-->
  7.   <product id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
  8.   <product id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
  9. <!--Australia-->
  10.   <product id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
  11. <!--Japan-->
  12.   <product id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
  13. </products>

Comment

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