I wish to create an if
statement without an else
portion in XQuery.
For example:
<results>
{
if (5 = 5) then
<foo/>
}
<results>
How do I do this?
I also tried this:
<results>
{
if (5 = 5) then
<foo/>
else
return
}
<results>
which although compiles, doesn't work when running!
There are no if
statements in XQuery without else
. Return the empty sequence instead ()
, or any reasonable identity element (which is usually what you will require if nothing specific is defined).
if ($foo eq "bar")
then
42
else
()
In contrast to procedural languages, where "no else statement" simply means "do nothing" XQuery is a functional language, which also implies that every operation must have "something" returned. How to proceed "nothing"? It might have been possible to declare "no else
statement means returning the empty sequence instead", but the W3C XML Query working group seems to have decided requiring to explicitely define returning nothing instead. All in all, this results in easier to understand and possibly better code, as you have to think about what the "else" value to return is; as there could be a lot of reasonable values: 0
if you're adding up something, 1
if multiplying, the empty string ""
for joining strings without separators, the empty sequence if joining strings with separators, ...
return
statements"Using an "empty" return is not possible, but returns <return/>
children elements in the current context instead, so else return
is merely a else ./return
. This will not only fail (and return something) if the current context indeed has <return/>
children, but also if no context at all is bound.
Returning an empty string does not return nothing, but the empty string, which is a value and might even break typing at another place. Returning the empty string is no general solution, but might be in some specific cases.
You could use a filter expression instead:
<results>
{
<foo/> [5 = 5]
}
</results>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With