Tag Archive for 'xsl'

07
Jan

XSLT Version of SQL SELECT MAX() and SELECT MIN()

I’ve frequently encountered the need to produce titles for XSLT produced tables.

For example, given the following XML:
<events>
<event date="2004-11-30 14:00:00" />
<event date="2004-11-30 14:00:00" />
<event date="2003-11-30 14:00:00" />
<event date="2002-11-30 14:00:00" />
</events>

To extract the values “2002″ and “2004″ to format a title such as “Events (2002 > 2004)”.

To do this effectively requires us to extract both the MAX and MIN values, for which we need an XSLT equivalent to the SQL SELECT MAX() and SELECT MIN() functions.

There is a neat trick to do this which can be summed up thus:

  • Sort ascending and pick the first node and you have your MIN.
  • Sort descending and pick the first node and you have your MAX.

Examples of both, given the above XML are here for your reference.

Obtaining the MIN:
<!-- Create a variable named $minEventDate containing the MIN date -->
<xsl:variable name="minEventDate">
<xsl:for-each select="event">
<xsl:sort select="@date" data-type="text" order="ascending" />
<xsl:if test="position() = 1">
<xsl:value-of select="@date" />
</xsl:if>
</xsl:for-each>
</xsl:variable>

Obtaining the MAX:
<!-- Create a variable named $maxEventDate containing the MAX date -->
<xsl:variable name="maxEventDate">
<xsl:for-each select="event">
<xsl:sort select="@date" data-type="text" order="descending" />
<xsl:if test="position() = 1">
<xsl:value-of select="@date" />
</xsl:if>
</xsl:for-each>
</xsl:variable>