w3pop.com :: ÍøÂçѧԺ :: Xquery :: 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> |
ÆÀÂÛ (0)
All