How to create an if statement without an else in XQuery?
Asked Answered
P

2

5

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!

Parasynapsis answered 2/12, 2015 at 14:3 Comment(0)
C
10

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, ...

Do not use "empty 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.

Do not return empty strings

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.

Caesalpiniaceous answered 2/12, 2015 at 14:47 Comment(0)
D
2

You could use a filter expression instead:

<results>
   { 
       <foo/> [5 = 5]
   }
</results>
Decastere answered 2/12, 2015 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.