Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test="" on a boolean always returns true

Why does

<xsl:if test="<XPATH to boolean value here>">
...
</xsl:if>

ALWAYS return true?

Since boolean can be 0,1,"false" and "true" by definition, the ONLY way to test for a boolean value is to do string comparison against these. This can't be right.

like image 844
Brian Johnson Avatar asked Jun 03 '10 20:06

Brian Johnson


People also ask

How do you check if a boolean is true or false?

An alternative approach is to use the logical OR (||) operator. To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean.

Can a boolean be in an if statement?

The simplest if-statement has two parts – a boolean "test" within parentheses ( ) followed by "body" block of statements within curly braces { }. The test can be any expression that evaluates to a boolean value – true or false – value (boolean expressions are detailed below).


1 Answers

The test specified in <xsl:if> works as if it called the boolean function. This function doesn't work the way you might think. If its argument evaluates to a node-set (which it will be if you use a path as its argument) it will return true if the node-set is not empty, and false otherwise. So effectively, you're testing for the existence of an element, not its value. If foo contains false,

<xsl:if test="/path/to/foo">

will always evaluate to true, since what you're really asking in that test is "does this element exist?" and not "is element's value true?" And the element exists.

The rule that boolean values must be true, false, 1, or 0 is a part of XML Schema (which see) and not XPath, which doesn't know anything about this rule. (XPath 1.0, that is. XPath 2.0/XQuery 1.0 has the fn:boolean function, which does smart, i.e. XML Schema aware, evaluation of boolean values.) To determine if a value is true in XSLT, you have to explicitly check it:

<xsl:if test="/path/to/foo = 'true' or /path/to/foo = '1'">
like image 110
Robert Rossney Avatar answered Oct 01 '22 02:10

Robert Rossney