XSLT : distinct / group by

Here's another useful piece of code i wrote today in order to implement a kind of distinct function using XSLT, that is, a template that returns each value only once. It can also be used to group elements together (much like the GROUP BY statement in SQL)

The technique is quite simple. The key resides in using an xsl key and the key() function.


<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s0="http://www.rmic.be/s0">
 <xsl:key name="my_key_name" match="s0:record" use="s0:some_element" />

 <xsl:template match="/">
  <out>
   <xsl:for-each select="//s0:record[count(. | key('my_key_name',s0:some_element)[1])=1]">
    <output_element>
     <xsl:value-of select="s0:some_element" />
    </output_element>
   </xsl:for-each>
  </out>
 </xsl:template>

</xsl:stylesheet>