Grouping in XSLT using the Muenchian Method

Beacon Blog Article

By Zedric Myers | Published January 10, 2013 | Categories:

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:
<p>&lt;contact id="0001"&gt;</p>
<p>&lt;contact id="0002"&gt;</p>
<p>&lt;/contact&gt; &lt;contact id="0003"&gt;</p>
<p>&lt;/contact&gt; &lt;contact id="0004"&gt;</p>
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
<p>&lt;xsl:stylesheet version="1.0" xmlns:xsl=""&gt;</p>
<p>&lt;xsl:key name="contacts-by-surname" match="contact" use="surname" /&gt;</p>
<p>&lt;xsl:template match="records"&gt;</p>
<p>&lt;xsl:for-each select="contact[count(. | key('contacts-by-surname', surname)[1]) = 1]"&gt;</p>
<p>&lt;xsl:sort select="surname" /&gt;</p>
<p>&lt;xsl:value-of select="surname" /&gt;,&lt;br /&gt;</p>
<p>&lt;xsl:for-each select="key('contacts-by-surname', surname)"&gt;</p>
<p>&lt;xsl:sort select="forename" /&gt;</p>
<p>&lt;xsl:value-of select="forename" /&gt; (&lt;xsl:value-of select="title" /&gt;)&lt;br /&gt; &lt;/xsl:for-each&gt;</p>
Third, the final output would look like this.
<p>Amy (Dr)</p>
<p>Brian (Mr)</p>
<p>Fiona (Ms)</p>
<p>John (Mr)</p>
The above information was provided by

Let's get to work!

Contact Us