How to create a boolean value?

sydlawrence picture sydlawrence · Dec 6, 2008 · Viewed 90.1k times · Source

I am totally new to XSLT and can't work out where I am going wrong with the following code.

<xsl:variable name="var" select="boolean('false')"/>

<xsl:if test="$var'">variable is true</xsl:if>

It is always returning true when it is meant to be false. Why?

Answer

Dimitre Novatchev picture Dimitre Novatchev · Dec 6, 2008

The value of the $var variable as defined in:

   <xsl:variable name="var" select="boolean('false')"/>

is

   true()

This is because in XPath "false" is an ordinary string, as opposed to false(), which is the constructor for the boolean value false()

The two boolean values in XPath are (note that they are constructed!):

   true() and false()

The detail of converting any value to boolean are spelled outin the XPath Spec.:

"The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN

  • a node-set is true if and only if it is non-empty

  • a string is true if and only if its length is non-zero

  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type "

In your case the string "false" is not the number 0 and has a positive length, so the rule in the 3rd bullet above is applied, yielding true().

Therefore, to define a variable in XSLT 1.0, whose value is false(), one needs to write the definition as the following:

   <xsl:variable name="vMyVar" select="false()"/>

or, if you don't exactly remember this, you could always write:

   <xsl:variable name="vMyVar" select="1 = 0"/>

(specify any expression that evaluates to false()) and the XSLT processor will do the work for you.

In XSLT 2.0 it is always better to explicitly specify the type of the variable:

   <xsl:variable name="vMyVar" as="xs:boolean" select="false()"/>