3

I am having an xml document in which there are some date nodes and I am trying to get their values if the values are valid dates otherwise empty string.

XML:

<root>
  <START_DATE><![CDATA[03/05/2015]]></START_DATE>
  <START_DATE><![CDATA[05/05/2015]]></START_DATE>
  <START_DATE><![CDATA[Online]]></START_DATE>
</root>

XSLT:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">
  <xsl:output method="text" indent="yes" />
  <xsl:template match="@*|node()">
    <xsl:apply-templates select="@*|node()" />
  </xsl:template>

  <xsl:template match="START_DATE">
    <xsl:copy>
        <xsl:value-of select="if(string(normalize-space(.)) castable as xs:date) then normalize-space(.) else ''"></xsl:value-of>
    </xsl:copy>
    <xsl:text>&#44;</xsl:text>
  </xsl:template>
</xsl:transform>

Output:

,,,

Expected:

03/05/2015,05/05/2015,,
Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46
  • Please indicate XSLT 1.0 or 2.0. Your stylesheet declares version 1.0, but it will only work with an XSLT 2.0 processor. Initially you have tagged this question `Xalan`, now you have removed this tag. Please clarify. – michael.hor257k May 08 '15 at 09:08
  • @michael.hor257k The processor is `Xalan` and I have tagged it. – Abhishekh Gupta May 08 '15 at 09:17

1 Answers1

5

get their values if the values are valid dates otherwise empty string

Xalan is an XSLT 1.0 processor. XSLT 1.0 has no concept of "date", so you will have to perform the validation yourself. The exact method depends on what exactly does "valid date" mean in this context.

If it's sufficient to ensure that the string purporting to be a date is formatted as a date (i.e. has exactly this pattern "##/##/####"), then the test can be quite simple:

<xsl:if test="translate(., '123456789', '000000000') = '00/00/0000'">
    <!-- result if valid -->
</xsl:if>

If you also need to test whether the purported date is a valid date in the Gregorian calendar (i.e. not "13/13/2015", for example), then it gets much more complicated.


A note about XSLT 2.0:

In XSLT 2.0, you can use castable as xs:date to test if a date is valid. However, even a valid date formatted as MM/DD/YYYY or DD/MM/YYYY will not pass this test. You must convert these strings to the YYYY-MM-DD format first.

michael.hor257k
  • 113,275
  • 6
  • 33
  • 51