XSLT: Get Latest Date
I have a structure like this:
<Info ID="1"> ... <Date>2009-04-21</Date> </Info> <Info ID="2"> ... <Date>2009-04-22</Date> </Info> <Info ID="3"> ... <Date>2009-04-20</Date> </Info> I want to get the latest date using XSLT (in this example, 2009-04-22).
I realized that it was not as difficult as I thought it would be:
<xsl:variable name="latest"> <xsl:for-each select="Info"> <xsl:sort select="Date" order="descending" /> <xsl:if test="position() = 1"> <xsl:value-of select="Date"/> </xsl:if> </xsl:for-each> </xsl:variable> <xsl:value-of select="$latest"/> XSLT 2.0+: <xsl:perform-sort> used when we want to sort the elements without processing the elements individually. <xsl:sort> used to process elements in sorted order. Since you just need the latest date in this case, you do not need to process each <Info> element. Use <xsl:perform-sort> :
<xsl:variable name="sorted_dates"> <xsl:perform-sort select="Info/Date"> <xsl:sort select="."/> </xsl:perform-sort> </xsl:variable> <xsl:value-of select="$sorted_dates/Date[last()]"/>