2014-02-17 74 views
0

如果輸入有效,則下面的代碼返回「TRUE」,但如果輸入錯誤則返回錯誤。例如,如果月份值爲15,則會引發錯誤。我怎樣才能返回錯誤而不是錯誤/異常?在XSLT 2.0中驗證日期時間

<xsl:template match="SUBSCRIBER"> 
    <xsl:variable name="date-iso" select="dm:stringToDateTime('20130327230844')"/> 
    <xsl:value-of select="($date-iso castable as xs:dateTime)"/> 
</xsl:template> 

<xsl:function name="dm:stringToDateTime"> 
    <!-- Convert string to date. Input format YYYYMMDDHHMMSS, Ex:20130116100037 --> 
    <xsl:param name="p_str" as="xs:string"/> 
    <xsl:value-of select="xs:dateTime(concat(substring($p_str,0,5),'-',substring($p_str,5,2),'-',substring($p_str,7,2),'T',substring($p_str,9,2),':',substring($p_str,11,2),':',substring($p_str,13,2)))"/> 
</xsl:function> 

回答

3

我覺得你嘗試使用xs:dateTime構造函數xs:dateTime(concat(substring($p_str,0,5),'-',substring($p_str,5,2),'-',substring($p_str,7,2),'T',substring($p_str,9,2),':',substring($p_str,11,2),':',substring($p_str,13,2)))會導致一個錯誤,如果你構建的字符串不是一個xs:dateTime。您需要更改的功能代碼,如果有可能的輸入格式是不是有效的xs:dateTime然後在功能不要試圖建構上,只返回與

<xsl:function name="dm:stringToDateTime"> 
    <!-- Convert string to date. Input format YYYYMMDDHHMMSS, Ex:20130116100037 --> 
    <xsl:param name="p_str" as="xs:string"/> 
    <xsl:sequence select="concat(substring($p_str,1,4),'-',substring($p_str,5,2),'-',substring($p_str,7,2),'T',substring($p_str,9,2),':',substring($p_str,11,2),':',substring($p_str,13,2))"/> 
</xsl:function> 

字符串,然後檢查

<xsl:template match="SUBSCRIBER"> 
    <xsl:variable name="date-iso" select="dm:stringToDateTime('20130327230844')"/> 
    <xsl:value-of select="($date-iso castable as xs:dateTime)"/> 
</xsl:template> 

當然,重命名該函數或者編寫第二個執行castable檢查可能會更好。

1

通過使用「castable as」,您有正確的想法,但您需要在嘗試投射之前進行此操作,而不是之後。類似於

<xsl:variable name="dt" select="concat(substring($p_str,0,5),'-',substring($p_str,5,2),'-',substring($p_str,7,2))"/> 
<xsl:sequence select="$dt castable as xs:dateTime"/>