最简单的图案将如下,创建用于每个可能的请求参数的变量(供给各作为空序列的默认值),然后返回子句中,在检查每个参数的存在,一个时间:
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