3

I'm using XSL's convenience functions for comparisons, gt, lt, ge, le, eq.

I understand these functions won't promote a string to a numerical value when performing comparisons, however I need that cast to be made, and I don't want to clutter my code with lines like

<xsl:when test="xs:integer($variable) lt 250" >

I'd rather make that cast like this (hypothetical of course)

<xsl:variable name="variable" type="xs:integer">

So, is there a means of explicitly casting variable as an numerical type when it is declared/created ?

JHarnach
  • 3,944
  • 7
  • 43
  • 48

1 Answers1

3
<xsl:when test="xs:integer($variable) lt 250" >

I'd rather make that cast like this (hypothetical of course)

<xsl:variable name="variable" type="xs:integer">

Use the as attribute -- its purpose is exactly to specify the type of a variable, parameter, template or a function:

<xsl:variable name="variable" as="xs:integer" 
              select="some-integer-type-expression">
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • @DimitreNovatchev but does it initialize the variable with some default value? Say for example I am assigning this variable some value based on condition and if thats not satisfied in that case will it be initialized to 0? – Paul Phoenix May 26 '17 at 06:06
  • @PaulPhoenix, There is no "default initialization" in XSLT -- because variables in XSLT cannot be changed -- they can have only the value they were given -- either with the `select` attribute, or inside their body, and this value can not be changed/re-assigned from this moment. XSLT is a functional programming language and variables are immutable.For more information how to "overcome" this immutability, see: https://stackoverflow.com/a/3345640/36305 – Dimitre Novatchev May 26 '17 at 13:47
  • 1
    @PaulPhoenix, Try having: ` ` in your code and also something that uses it as integer, for example: `` . You'll get a compile-time error like this (from Saxon 9.1J): "Error at xsl:variable on line 7 column 46 of yourfile.xsl: XTTE0570: The implicit value () is not valid for the declared type Failed to compile stylesheet. 1 error detected." – Dimitre Novatchev May 26 '17 at 13:53