当前位置: 首页 > 网络学院 > XML相关教程 > Xquery > XQuery 选择和过滤
As we have seen in the previous chapters, we are selecting and filtering elements with either a Path expression or with a FLWOR expression.
如同在前几章里所看到的那样,我们使用路径表达式或FLWOR表达式来选择和过滤元素。
Look at the following FLWOR expression:
先看看下面的FLWOR表达式:
for $x in doc("books.xml")/bookstore/book |
The for clause binds a variable to each item returned by the in expression. The for clause results in iteration. There can be multiple for clauses in the same FLWOR expression.
给从 “in 表达式” 中返回每一个项绑定一个变量。For子句会导致重复。在相同的FLWOR表达式中,可以包含多个for子句。
To loop a specific number of times in a for clause, you may use the to keyword:
在for子句中对一个指定的数字进行多次循环,你可以使用关键词 “ to ”:
for $x in (1 to 5) |
Result:
结果:
<test>1</test> |
The at keyword can be used to count the iteration:
关键字 “at” 可用于计算重复次数:
for $x at $i in doc("books.xml")/bookstore/book/title |
Result:
结果如下:
<book>1. Everyday Italian</book> |
It is also allowed with more than one in expression in the for clause. Use comma to separate each in expression:
在for子句中,允许出现一项或多项 “in 表达式”;使用逗号将表达式中的每项分开:
for $x in (10,20), $y in (100,200) |
Result:
结果如下:
<test>x=10 and y=100</test> |
The let clause allows variable assignments and it avoids repeating the same expression many times. The let clause does not result in iteration.
Let 子句允许变量分配,目的是为了避免多次重复执行相同的表达式。Let子句不会引起反复:
let $x := (1 to 5) |
Result:
结果如下:
<test>1 2 3 4 5</test> |
The where clause is used to specify one or more criteria for the result:
Where 子句的作用是给结果指定一个或多个标准。
where $x/price>30 and $x/price<100 |
The order by clause is used to specify the sort order of the result. Here we want to order the result by category and title:
order by 子句用于为输出的结果指定排列的次序。在这里,我们希望使用“目录”和“标题”对结果进行排列:
for $x in doc("books.xml")/bookstore/book |
Result:
结果如下:
<title lang="en">Harry Potter</title> |
The return clause specifies what is to be returned.
Return 子句指定了返回的值。
for $x in doc("books.xml")/bookstore/book |
Result:
结果如下:
<title lang="en">Everyday Italian</title> |