XQuery/Ah-has

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Redundancy in Expressions[edit | edit source]

let $r := if ($x = 1) then true() else false();

better as

let $r := ($x = 1)

and

 for $p in (0 to string-length($arg1)) return $p

better as

 (0 to string-length($arg1))

and

 for $i in (1 to 5)
 return
     for $j in (11 to 15)
     return
         ($i, $j)

better as

 for $i in (1 to 5), $j in (11 to 15)
 return
     ($i, $j)

OR

 for $i in (1 to 5) 
 for $j in (11 to 15)
 return
     ($i, $j)

all three return

 (1 11 1 12 1 13 1 14 1 15 2 11 2 12 2 13...)

XPath predicates clearer and faster than where clauses[edit | edit source]

 for $x in //Page 
 where $x/heading = 1
 return $x

better as

 //Page[heading = 1]

Default values[edit | edit source]

 if (exists($a)) then $a else "Default" 

better as

 ($a,"Default") [1]

OR for a sequence of items

 ($list1, "Default"[empty($list1)])

OR another possible for a sequence

 (<test/>,<test/>,<default/>)[not(position() = last() and not(last() = 1))]

any number of cascaded defaults can be handled this way.

compare with 'COALESCE' in SQL