0

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:

Mohsen Safari
  • 6,669
  • 5
  • 42
  • 58
Rick
  • 15
  • 1
  • 4

1 Answers1

0

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • Thanks, Ian. I should have specified, this is XSLT 1.0. – Rick Mar 07 '13 at 19:48
  • The inputs won't ever be too large, the full file I pulled this example data from is only 339 lines, and most of the time there will be between 1-4 instances of the servicePeriod dates. You're example/idea is awesome, but I'm pulling an empty string with it. DOH, I need to update the names, being lazy..... – Rick Mar 07 '13 at 21:18