Latest web development tutorials

XQuery Selecting and Filtering

XML instance documents

In the following example we will continue to use this "books.xml" (same XML file and the section above is used) document.

See "books.xml" file in your browser .


Select and filter elements

As seen in the previous chapter, we use the FLWOR expression or a path expression to select and filter elements.

Consider 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) to each of the bundled items returned by the expression in a variable
  • let - (optional)
  • where - (optional) set a condition
  • order by - (optional) set the order in the results
  • return - the provisions in the results returned content

for statement

statement for the variable tied to each item returned by the in expression. for statement Iteration. There may be multiple for the same statement in a FLWOR expression.

For a specified number of times in a for statement to loop, you can use keywords 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 can be used to calculate the iteration at:

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>

In the statement also allows for more than one in expression. Please use a comma 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

let statement can be complete variable distribution, and avoid repeated the same expression. let statement does not cause iteration.

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

result:

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

where statements

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

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

order by statement

order by statement to sort the results of a predetermined order. Here, we want 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:

return statement specifies to return the contents.

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>