XQuery Tutoriallogin
XQuery Tutorial
author:php.cn  update time:2022-04-21 16:43:44

XQuery selection and filtering



XML Example Document

We will continue to use this "books.xml" document in the following examples (the same XML file used in the above chapters).

View the "books.xml" file in your browser.


Selecting and filtering elements

As seen in the previous chapters, we use path expressions or FLWOR expressions to select and filter elements.

See the following FLWOR expression:

for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
  • for - (optional) Bundle a variable to each item returned by the in expression

  • let - (optional)

  • where - (optional) Set a condition

  • order by - (optional) Set the order in which the results are sorted

  • return - Specify the content returned in the results

for statement

The for statement binds variables to each item returned by the in expression. The for statement produces iteration. Multiple for statements can exist in the same FLWOR expression.

To loop a specified number of times in a for statement, you can use the keyword 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>
Keywords

at Can be used to calculate iterations:

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>
Multiple in expressions are also allowed in the for statement. 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 completes variable assignment and avoids 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

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

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

order by statement

order by statement is used to specify the ordering of results order. Here, we need to sort the results according to 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>