Changes

Jump to navigation Jump to search
1,094 bytes added ,  22:32, 2 November 2012
This page contains code snippets that mainly originate from our [https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk basex-talk] mailing list.
 
== If, then, else ==
 
<code>if</code>/<code>not</code>/<code>else</code> constructs can look pretty verbose in XQuery.
However, some alternatives exist in order to make conditional code more compact:
 
* The [[XQuery 3.0#Simple Map Operator|Simple Map Operator]] can be used to trigger an action if a value has a single item. The following two expressions are equivalent:
 
<pre class="brush:xquery">
let $s := "X" return (
(: OLD :) if(count($s) = 1) then 'OK' else (),
(: NEW :) $s ! 'OK'
)
</pre>
 
In some cases, also the first solution can be written more compact. If we know that our input will always have 0-1 items, we can write <code>if(exists($s))</code>. If our input will never be an empty string, a zero, etc, it’s sufficient to write <code>if($s)</code>.
 
* If you want to choose the first non-empty item from two arguments, we can use the position predicate:
 
<pre class="brush:xquery">
let $s := "X" return (
(: OLD :) if(exists($s)) then $s else 'default',
(: NEW :) ($s, 'default')[1]
)
</pre>
 
Note that this only works if both of your inputs have zero or one items.
== Computed Elements ==
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu