XSLT/Muenchian grouping
Muenchian grouping (or Muenchian method, named after Steve Muench) is an algorithm for grouping of data used in XSL Transformations v1 that identifies keys in the results and then queries all nodes with that key. This improves the traditional alternative for grouping, whereby each node is checked against previous (or following) nodes to determine if the key is unique (if it is, this would indicate a new group).[1] In both cases the key can take the form of an attribute, element, or computed value.
The unique identifier is referred to as a key because of the use of the 'key' function to identify and track the group variable.
The technique is not necessary in XSLT 2.0+, which introduces the new for-each-group
tag.
General aspect of the transform
The method took advantage of XSLT's ability to index documents using a key. The trick involves using the index to efficiently figure out the set of unique grouping keys and then using this set to process all nodes in the group:[2]
<xsl:key name="products-by-category" match="product" use="@category"/>
<xsl:template match="/">
<xsl:for-each select="//product[count(. | key('products-by-category', @category)[1]) = 1]">
<xsl:variable name="current-grouping-key"
select="@category"/>
<xsl:variable name="current-group"
select="key('products-by-category',
$current-grouping-key)"/>
<xsl:for-each select="$current-group">
<!-- processing for elements in group -->
<!-- you can use xsl:sort here also, if necessary -->
</xsl:for-each>
</xsl:for-each>
</xsl:template>
Although the Muenchian method will continue to work in 2.0, for-each-group
Is preferred as it is likely to be as efficient and probably more so. The Muenchian method can only be used for value-based grouping.