mercoledì, settembre 29, 2010

XSLT Grouping: the Muenchian Method

Jeni's XSLT Pages has an extremely useful article on how to take a list of XML elements and arrange them into groups.

http://www.jenitennison.com/xslt/grouping/muenchian.html

“The Muenchian Method is a method developed by Steve Muench for performing these functions in a more efficient way using keys. Keys work by assigning a key value to a node and giving you easy access to that node through the key value. If there are lots of nodes that have the same key value, then all those nodes are retrieved when you use that key value. Effectively this means that if you want to group a set of nodes according to a particular property of the node, then you can use keys to group them together.”

An example from her article:

<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>