Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XSLT

Grouping XML elements using XSLT version 1.0

5.00/5 (3 votes)
6 Nov 2011CPOL 35.2K  
A quick example of how to do grouping in XSLT version 1.0

Suppose you have an XML like:


XML
<Rows>
    <Row Category="Sweet" Value="Chocolate" />
    <Row Category="Salty" Value="Potato Chips" />
    <Row Category="Salty" Value="Pop Corn" />
    <Row Category="Sour" Value="Lemon" />
    <Row Category="Sweet" Value="Biscuits" />
    <Row Category="Salty" Value="Fries" />
</Rows>

and you want to have these rows grouped by the 'Category' attribute like:


Salty
--------
Fries
Pop Corn
Potato Chips

Sour
--------
Lemon

Sweet
--------
Biscuits
Chocolate

You can use Muenchian grouping just like the following:


XML
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

  <!-- First, define a key that uses our element or attribute we need to group by. In our case it's the Category attribute. -->
  <xsl:key name="food-by-Category" match="Row" use="@Category" />

  <xsl:template match="Rows">
    <!-- Now, we need to iterate on the Categories, This can be done by iterating on the first XML Row item 
         for each Category. We will do that by create a node set for the current Row item (.) and the first 
         item in the Key of the Current item  Category. Then we check the count to see is it 1 or 2.. 
         If 1, So we've the same item in the node set; We have a new Category.-->
    <xsl:for-each select="Row[count(. | key('food-by-Category', @Category)[1]) = 1]">
      <!-- Sort by the Category -->
      <xsl:sort select="@Category" />
      <xsl:value-of select="@Category" />
      <hr />
      <!-- Now loop on the items of this Category, 
                  We get them from the Key we defined -->
      <xsl:for-each select="key('food-by-Category', @Category)">
        <!-- Sort by the item Value -->
        <xsl:sort select="@Value" />
        <xsl:value-of select="@Value" />
        <br />
      </xsl:for-each>
      <br />
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)