8

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

Mindaugas Mozūras
  • 1,461
  • 2
  • 17
  • 29

3 Answers3

17

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"/>
Mindaugas Mozūras
  • 1,461
  • 2
  • 17
  • 29
7

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(.))"/>
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • Interesting. 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? – moritz.vieli Apr 13 '20 at 07:59
5

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()]"/>
bluish
  • 26,356
  • 27
  • 122
  • 180
Pete
  • 16,534
  • 9
  • 40
  • 54