最簡單的圖案將如下,創建用於每個可能的請求參數的變量(供給各作爲空序列的默認值),然後返回子句中,在檢查每個參數的存在,一個時間:
xquery version "3.0";
let $albums := doc("music.xml")//music/album
let $type := request:get-parameter('type',())
let $title := request:get-parameter('title',())
let $artist := request:get-parameter('artist',())
return
if ($type) then
$albums[type = $type]
else if ($title) then
$albums[title = $title]
else if ($artist) then
$albums[artist = $artist]
else
$albums
此代碼假定<type>
,<title>
,和<artist>
是<album>
子元素,我們檢查了提供的參數完全匹配。你可以改變title = $title
比較contains(title, $title)
爲區分大小寫的文字字符串匹配,matches(title, $title, 'i')
爲不區分大小寫的正則表達式搜索,或全文索引像ft:query(title, $title)
,如果你配置了索引全文索引上<title>
元素等
的這種方法的弱點在於,我們對影響查詢的參數進行了嚴格的嚴格優先級排序。如果提供了type
參數,則即使提供title
和album
的查詢也不會被考慮。
要鏈接在一起,這樣任何和所有提供的參數進行查詢,你可以採取以下方法:
xquery version "3.0";
let $albums :=
<albums>
<album><type>country</type><title>Holiday Classics</title><artist>Jane</artist></album>
<album><type>country</type><title>Lonesome Cowboy</title><artist>Jim</artist></album>
<album><type>country</type><title>Lonesome Holiday</title><artist>Jane</artist></album>
</albums>//album
let $type := request:get-parameter('type',())
let $title := request:get-parameter('title',())
let $artist := request:get-parameter('artist',())
return
$albums
[if ($type) then type = $type else true()]
[if ($title) then title = $title else true()]
[if ($artist) then artist = $artist else true()]
我提供的樣本數據只是爲了確認自己和他人的測試,這一工作的代碼。只有提供參數時纔會評估return子句中的比較。此代碼假設每個參數最多一個值;如果您爲每個參數允許多個值,則需要進行一些調整。
謝謝@joewiz,你是我的救星:) – yenerunver
好聽;) – joewiz