XSL Transform extracting min and max dates

2019-08-20 23:09发布

I'm trying to extract min and max dates from an XML source. I'm getting a nodeset into my variables and I need the actual date value within the nodes and can't find how to get it.

Source XML:

<Info dataSource="source">
<Detail>
    <StartDate>20121211</StartDate>
    <EndDate>20130112</EndDate>
</Detail>
<Detail>
    <StartDate>20121211</StartDate>
    <EndDate>20130112</EndDate>
</Detail>
<Detail>
    <StartDate>20121211</StartDate>
    <EndDate>20130112</EndDate>
</Detail>
<Detail>
    <StartDate>20121218</StartDate>
    <EndDate>20130114</EndDate>
</Detail>
</Info>

The XSL code:

  <xsl:if test="//StartDate != '' and //EndDate != ''">
    <xsl:variable name ="startDate">
      <xsl:for-each select="//StartDate">
        <xsl:sort select="StartDate" data-type="text" order="ascending"/>
        <xsl:if test="position() = 1">
          <xsl:value-of select="." />
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>
    <xsl:variable name ="endDate">
      <xsl:for-each select="//EndDate">
        <xsl:sort select="EndDate" data-type="text" order="descending"/>
        <xsl:if test="position() = 1">
          <xsl:value-of select="." />
        </xsl:if>
      </xsl:for-each>
    </xsl:variable> 
  </xsl:if>

The dates are formatted correctly to support the sorts and retrieval, the issue is once the variables are populated I can't find how to access their values:

1条回答
smile是对你的礼貌
2楼-- · 2019-08-20 23:40

If you're using XSLT 2.0 you have min and max functions which do the work for you. XSLT 1.0 doesn't have these functions, but you can cheat by doing this (may be rather inefficient for large inputs, but it works):

<xsl:variable name="startDate" select="string(//StartDate[not(. > //StartDate)])" />

and similarly for the endDate. The trick here is that you're looking for the StartDate d for which there is no other StartDate that d is greater than.

查看更多
登录 后发表回答