XSLT: Getting the latest date

2019-04-08 01:58发布

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

标签: xml xslt sorting
3条回答
我只想做你的唯一
2楼-- · 2019-04-08 02:39

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()]"/>
查看更多
ら.Afraid
3楼-- · 2019-04-08 02:41

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(.))"/>
查看更多
女痞
4楼-- · 2019-04-08 02:44

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"/>
查看更多
登录 后发表回答