Logical expressions combine Boolean values using the operators and
and or
. They are most often used in conditional (if-then-else
) expressions, where
clauses of FLWORs and path expression predicates. However, they can be used anywhere a Boolean value is expected.
For example, when used in a conditional expression:
if ($isDiscounted and
$discount > 10) then 10 else $discount
an and
expression returns true if both of its operands are true. An or
expression evaluates to true if one or both of its operands is true.
As with conditional test expressions, the effective Boolean value of each of the operands is evaluated. This means that if the operand expression evaluates to a Boolean false
value, the number 0 or NaN
, a zero-length string, or the empty sequence, it is considered false; otherwise, it is generally considered true. For example:
$order/item and $numItems
returns true
if there is at least one item
child of $order
, and $numItems
(assuming it is numberic) is not equal to 0 or NaN
(i.e., not a number).
The logical operators have lower precedence than comparison operators do, so you can use:
if ($x<
12and
$y>
15) then ...
without parenthesizing the two comparison expressions.
You can also chain multiple and
and or
expressions together. The and
operator takes precedence over the or
operator. Therefore:
true( )and
true( )or
false( )and
false( )
is the same as:
(
true( )and
true( ))
or (
false( )and
false( ))
and evaluates to true
. It is not equal to:
true( )and
(
true( )or
false( ))
and
false( )
which evaluates to false
.
You can negate any Boolean value by using the not
function, which turns false
to true
and true
to false
. Because not
is a function rather than a keyword, you are required to use parentheses around the value that you are negating.
The function accepts a sequence of items, from which it calculates the effective Boolean value before negating it. This means that if the argument evaluates to the xs:boolean
value false
, the number 0 or NaN
, a zero-length string, or the empty sequence, the not
function returns true. In most other cases, it returns false.
Table 3-5 shows some examples of the not
function.
There is a subtle but important difference between using the !=
operator and calling the not
function with an expression that uses the =
operator. For example, the expression $prod/@dept != 'ACC'
returns:
true
if the $prod
element has a dept
attribute that is not equal to ACC
false
if it has a dept
attribute that is equal to ACC
false
if it does not have a dept
attribute
On the other hand, not($prod/@dept = 'ACC')
will return true
in the third case—that is, if the $prod
element does not have a dept
attribute. This is because the $prod/@dept
expression returns the empty sequence, which results in the comparison evaluating to false
. The not
function will negate this and return true
.
3.135.191.86