Grouping in XSLT using the Muenchian Method

Est. Reading Time: 2 minutes

Have you ever wanted to group lists of information in XSLT? We do know that it’s a common issue in XSLT 1.0. There is a method to help with this called the “Muenchian Method” named after the developer, Steve Muench.

In this example we will cover the standard grouping method that is commonly used. The method involves generating a key and assigning it to “for-each” statements to handle the grouping.

For this particular example we will be grouping a mock address book by “surname” and sorting by “forename”.

 

First, start with standard flat input from the XML:

<records>
   <contact id="0001">
      <title>Mr</title>
      <forename>John</forename>
      <surname>Smith</surname>
   </contact>
   <contact id="0002">
      <title>Ms</title>
      <forename>Fiona</forename>
      <surname>Smith</surname>
   </contact>
   <contact id="0003">
      <title>Dr</title>
      <forename>Amy</forename>
      <surname>Jones</surname>
   </contact>
   <contact id="0004">
      <title>Mr</title>
      <forename>Brian</forename>
      <surname>Jones</surname>
   </contact>
</records>

Second, create the XSLT template with the key at the top, “for-each” statement with the grouping method applied and the final “for-each” statement that groups the desired element.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:key name="contacts-by-surname" match="contact" use="surname" />
   <xsl:template match="records">
      <xsl:for-each select="contact[count(. | key('contacts-by-surname', surname)[1]) = 1]">
         <xsl:sort select="surname" />
         <xsl:value-of select="surname" />,<br />
         <xsl:for-each select="key('contacts-by-surname', surname)">
            <xsl:sort select="forename" />
            <xsl:value-of select="forename" /> (<xsl:value-of select="title" />)<br />
         </xsl:for-each>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

Third, the final output would look like this.

Jones,
   Amy (Dr)
   Brian (Mr)

Smith,
   Fiona (Ms)
   John (Mr)

The above information was provided by www.jenitennison.com.