Home > database >  How to use xsl:try and xsl:catch in XSLT3.0?
How to use xsl:try and xsl:catch in XSLT3.0?

Time:09-26

I am trying to experiment with XSLT 3.0 here at https://xsltfiddle.liberty-development.net/ .

I got this error:

Error executing XSLT at line 9 : Cannot convert string "INF" to xs:decimal: invalid character 'I'

Here is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<division>
  <num1>9999</num1>
  <num2>0</num2>
</division>

Here is my XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="3.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"    
      xmlns:xs="http://www.w3.org/2001/XMLSchema" 
      xmlns:fn="http://www.w3.org/2005/xpath-functions"
      xmlns:err="http://www.w3.org/2005/xqt-errors"
      xmlns:ns ="http://example.com">

   <xsl:function name="ns:divide" as="xs:decimal">
     <xsl:param name="x" as="xs:double"/>
     <xsl:param name="y" as="xs:double"/>
     <xsl:value-of select="$x div $y"/>     
   </xsl:function>
 
   <xsl:template match="division">hi
      <xsl:if test="num1 > 999 or num2 > 999">
         One or two of the integers are greater than 999. 
      </xsl:if>
      <xsl:try select="ns:divide(num1,num2)">
         <xsl:catch errors="err:FAOR0001">
           <xsl:message>Division by zero.
             Code: <xsl:value-of select="$err:code"/>
             Description: <xsl:value-of select="$err:description"/>
             Value: <xsl:value-of select="$err:value"/>
             Module: <xsl:value-of select="$err:module"/>
             Line-number: <xsl:value-of select="$err:line-number"/>
             Column-number: <xsl:value-of select="$err:column-number"/>
           </xsl:message>
         </xsl:catch>
      </xsl:try>
   </xsl:template>
</xsl:transform>

CodePudding user response:

The error happens due to your function's as="xs:decimal" return type declaration, trying to cast the result of the division to xs:decimal fails.

I think what you want do to is e.g. (note the changed error code and the casting)

   <xsl:template match="division">
      <xsl:try select="xs:integer(num1) div xs:integer(num2)">
         <xsl:catch errors="err:FOAR0001">
           <xsl:message>Division by zero.
             Code: <xsl:value-of select="$err:code"/>
             Description: <xsl:value-of select="$err:description"/>
             Value: <xsl:value-of select="$err:value"/>
             Module: <xsl:value-of select="$err:module"/>
             Line-number: <xsl:value-of select="$err:line-number"/>
             Column-number: <xsl:value-of select="$err:column-number"/>
           </xsl:message>
         </xsl:catch>
      </xsl:try>
   </xsl:template>

Run it from the command line or with oXygen to see the xsl:message output.

  • Related