YouTip LogoYouTip

Xquery Select

XML Example Document

We will continue using the "books.xml" document in the examples below (the same XML file used in the previous chapter). View the "books.xml" file in your browser.

Selecting and Filtering Elements

As seen in previous chapters, we use path expressions or FLWOR expressions 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) binds a variable to each item returned by the in expression
  • let - (optional)
  • where - (optional) sets a condition
  • order by - (optional) specifies the sort order of the result
  • return - specifies what to return in the result

The for Clause

The for clause binds a variable to each item returned by the in expression. The for clause enables iteration. Multiple for clauses can exist within the same FLWOR expression.

To loop a specific number of times in a for clause, 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>

The keyword at can be used to count 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 a for clause. 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>

The let Clause

The let clause assigns values to variables and helps avoid repeating the same expression multiple times. The let clause does not cause iteration.

let $x := (1 to 5)

 return <test>{$x}</test>

Result:

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

The where Clause

The where clause is used to specify one or more conditions (criteria) for the result.

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

The order by Clause

The order by clause specifies the sort order of the result. Here, we sort the result 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>

The return Clause

The return clause specifies what to return.

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>
← Schema IntroXquery Add β†’