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).
(You can get the details of the default timezone with the implicit-timezone() function). The current-date() function returns the same value throughout the processing of the stylesheet. If you call current-date() a dozen times throughout your stylesheet, the function returns the same value each time.
XSLT is very widely used. As far as we can judge from metrics like the number of StackOverflow questions, it is in the top 30 programming languages, which probably makes it the top data-model-specific programming language after SQL. But XSLT isn't widely used client-side, that is, in the browser.
Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*
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"/>
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(.))"/>
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()]"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With