跳轉到內容

XQuery/妙招

來自 Wikibooks,開放世界中的開放書籍

表示式中的冗餘

[編輯 | 編輯原始碼]
let $r := if ($x = 1) then true() else false();

最好是

let $r := ($x = 1)

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

最好是

 (0 to string-length($arg1))

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

最好是

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

或者

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

所有這三種都返回

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

XPath 謂詞比 where 子句更清晰、更快

[編輯 | 編輯原始碼]
 for $x in //Page 
 where $x/heading = 1
 return $x

最好是

 //Page[heading = 1]

預設值

[編輯 | 編輯原始碼]
 if (exists($a)) then $a else "Default" 

最好是

 ($a,"Default") [1]

或者用於項序列

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

或者另一個可能的用於序列

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

任何數量的級聯預設值都可以透過這種方式處理。

與 SQL 中的 "COALESCE" 相比較

華夏公益教科書