XSLT: Getting the latest date
13,197
Solution 1
Figured it out, wasn't as hard as I thought it will 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"/>
Solution 2
In XSLT 2.0 or later, you shouldn't need to sort at all; you can use max()
...
<xsl:value-of select="max(//Date/xs:date(.))"/>
Solution 3
XSLT 2.0+: <xsl:perform-sort>
is used when we want to sort elements without processing the elements individually. <xsl:sort>
is used to process elements in sorted order. Since you just want the last 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()]"/>
Author by
Mindaugas Mozūras
Updated on July 28, 2022Comments
-
Mindaugas Mozūras almost 2 years
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).
-
Tomalak over 9 yearsYou should note that this is XSLT 2.0 and up.
-
Robert Smit over 8 yearsWhen faced with a different date format(in my case dd-mm-yyyy) the following sort worked for me:
<xsl:sort select="number(concat(substring(Date,7,4),substring(Date,4,2),substring(Date,1,2)))" order="descending" />
-
moritz.vieli about 4 yearsInteresting. I did not know about the "/xs:date(.)"-casting. Until now, I only used xs:date(xy), but this style does not accept multiple elements. Is there a namy for this kind of casting?