xml - Check whether a string is a valid date or not in XSLT -


i having xml document in there date nodes , trying values if values 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 xs:date) 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,, 

get values if values valid dates otherwise empty string

xalan xslt 1.0 processor. xslt 1.0 has no concept of "date", have perform validation yourself. exact method depends on "valid date" mean in context.

if it's sufficient ensure string purporting date formatted date (i.e. has pattern "##/##/####"), test can quite simple:

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

if need test whether purported date valid date in gregorian calendar (i.e. not "13/13/2015", example), gets more complicated.


a note xslt 2.0:

in xslt 2.0, can use castable xs:date test if date valid. however, valid date formatted mm/dd/yyyy or dd/mm/yyyy not pass test. must convert these strings yyyy-mm-dd format first.


Comments