Grouping in XSLT using the Muenchian Method

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:
<records>
<p>&lt;contact id="0001"&gt;</p>
<p>&lt;title&gt;Mr&lt;/title&gt;</p>
<p>&lt;forename&gt;John&lt;/forename&gt;</p>
<p>&lt;surname&gt;Smith&lt;/surname&gt;</p>
<p>&lt;/contact&gt;</p>
<p>&lt;contact id="0002"&gt;</p>
<p>&lt;title&gt;Ms&lt;/title&gt;</p>
<p>&lt;forename&gt;Fiona&lt;/forename&gt;</p>
<p>&lt;surname&gt;Smith&lt;/surname&gt;</p>
<p>&lt;/contact&gt; &lt;contact id="0003"&gt;</p>
<p>&lt;title&gt;Dr&lt;/title&gt;</p>
<p>&lt;forename&gt;Amy&lt;/forename&gt;</p>
<p>&lt;surname&gt;Jones&lt;/surname&gt;</p>
<p>&lt;/contact&gt; &lt;contact id="0004"&gt;</p>
<p>&lt;title&gt;Mr&lt;/title&gt;</p>
<p>&lt;forename&gt;Brian&lt;/forename&gt;</p>
<p>&lt;surname&gt;Jones&lt;/surname&gt;</p>
<p>&lt;/contact&gt;</p>
&lt;/records&gt;
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="http://www.w3.org/1999/XSL/Transform"&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>
<p>&lt;/xsl:for-each&gt;</p>
<p>&lt;/xsl:template&gt;</p>
&lt;/xsl:stylesheet&gt;
Third, the final output would look like this.
<p>Jones,</p>
<p>Amy (Dr)</p>
<p>Brian (Mr)</p>
<p>&amp;#160;</p>
<p><br/>Smith,</p>
<p>Fiona (Ms)</p>
<p>John (Mr)</p>
The above information was provided by www.jenitennison.com.

Contact Us To Find Out More

Have questions? Need help? Contact us and we'll be in touch soon!

* Required

Beacon
164 Thatcher Road
Greensboro, NC 27409
Map and Directions

Sales & Marketing
336.232.5687