Search code examples
validationdatexsltxslt-1.0ibm-datapower

Unable to use fn:cast and castable in XSLT


I am trying to convert a string to date using castable function in XSLT. But i am getting a parsing error. I am using DataPower XI52 version 6.0.1.0. Does XI52 support this function?

Sample XML:

<Input><Date>2011-31-12</Date></Input>

My XSLT:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="/">
    <xsl:variable name="Date" select="Input/Date"/>
    <xsl:value-of select="fn:cast($Date,'xs:string','xs:date', true())"/>
    </xsl:template>
</xsl:stylesheet>

Solution

  • If (as it seems) you are trying to determine if the input contains a valid date - i.e. the equivalent of:

    XSLT 2.0

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:template match="/">
        <xsl:variable name="Date" select="Input/Date"/>
        <xsl:value-of select="$Date castable as xs:date"/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    then try the following:

    XSLT 1.0 (+ EXSLT)

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:date="http://exslt.org/dates-and-times"
    extension-element-prefixes="date">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:template match="/">
        <xsl:variable name="Date" select="Input/Date"/>
        <xsl:value-of select="boolean(date:date($Date))"/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    This should work with any XSLT 1.0 processor that supports the EXSLT date:date() extension function, incl. IBM DataPower.

    Note however, that it does NOT work with Saxon 6.5.5 that will happily output 2011-31-12 as the result of <xsl:value-of select="date:date('2011-31-12')"/> - despite the specification prescribing an empty string as the required result in this case.