XQuery Selectie en Filteren

XML实例文档

我们将在下面的例子中继续使用这个 "books.xml" 文档(和上面的章节所使用的 XML 文件相同)。

在您的浏览器中查看 "books.xml" 文件

选择和过滤元素

正如在前面的章节所看到的,我们使用路径表达式或 FLWOR 表达式来选择和过滤元素。

请看下面的 FLWOR 表达式:

for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
for
(可选) 向每个由 in 表达式返回的项目绑定一个变量
let
(可选)
where
(可选) 设定一个条件
order by
(可选) 设定结果的排列顺序
return
规定在结果中返回的内容

for 语句

for 语句可以将变量绑定到由 in 表达式返回的每个项目。for 语句可以产生迭代。在同一个 FLWOR 表达式中可以存在多个 for 语句。

如果需要在 for 语句中指定次数地循环,您可以使用关键词 to

for $x in (1 to 5)
return <test>{$x}</test>

Result:

<test>1</test>
<test>2</test>
<test>3</test>
<test>4</test>
<test>5</test>

Keyword at Can be used to calculate iteration:

for $x at $i in doc("books.xml")/bookstore/book/title
return <book>{$i}. {data($x)}</book>

Result:

<book>1. Everyday Italian</book>
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>

Similarly in the for statementMultiple in expressions are allowed. Please use commas to separate each in expression:

for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>

Result:

<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>

Let statement

The let statement can perform variable assignment and can avoid repeating the same expression multiple times. The let statement does not cause iteration.

let $x := (1 to 5)
return <test>{$x}</test>

Result:

<test>1 2 3 4 5</test>

Where statement

The where statement is used to set one or more conditions (criteria) for the results.

where $x/price>30 and $x/price<100

Order by statement

The order by statement is used to specify the order of the results. Here, we want to sort the results by category and title:

for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title

Result:

<title lang="en">Harry Potter</title>
<title lang="en">Everyday Italian</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>

Return statement:

The return statement specifies the content to be returned.

for $x in doc("books.xml")/bookstore/book
return $x/title

Result:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>