Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: Getting the latest date

Tags:

sorting

xml

xslt

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).

like image 352
Mindaugas Mozūras Avatar asked Mar 26 '09 08:03

Mindaugas Mozūras


People also ask

How do I get todays date in XSLT?

(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.

Does anyone use XSLT anymore?

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.

What is current group () in XSLT?

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()*


3 Answers

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"/>
like image 119
Mindaugas Mozūras Avatar answered Nov 15 '22 22:11

Mindaugas Mozūras


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(.))"/>
like image 28
Daniel Haley Avatar answered Nov 15 '22 21:11

Daniel Haley


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()]"/>
like image 44
Pete Avatar answered Nov 15 '22 20:11

Pete