XQuery

Version 1.11

Handouts/examples:

Individual files:

Introduction

XQuery builds on the XPath language extending it to build so-called FLWOR (“flower”) expressions which are similar in function to the SQL select statement.

FLWOR expressions

FLWOR stands for for, let, where, order by, and return; expressions are built out of clauses beginning with these words. The for and return clauses are required; the rest are optional.

Using the for and return clauses

The for clause creates variables using XPath expressions; it tells where the data comes from, and thus functions like the from clause in an SQL select statement. The return clause specifies what is to be output.

Simple example: for-ret1.xq, using pets.xml as the source document

Using XQilla

XQilla (xqilla) is a command-line tool which can run XQuery expressions.

Simple usage: to run an XQuery query from file query.xq with an input XML document source.xml:

$ xqilla -i source.xml query.xq

The preceding command will produce unformatted output which is hard to read. To make the output prettier, filter it through xmllint as follows:

$ xqilla -i source.xml query.xq | xmllint --format -

The final - tells xmllint to read from stdin. You can, of course, also pipe the output through less or redirect it to an output file.

These scripts can be helpful:

Inserting tags and data

Using the let clause

The let clause introduces (local) variables in the query.

Using the order by clause

The order by clause, like in SQL, specifies how to sort the output.

Using the where clause

The where clause, like in SQL, specifies conditions for selecting elements for output:

But you don’t always need to use where for this, because XPath expressions can imply conditions as well:

Concluding example

The last example uses all the FLWOR parts. Remember, FLWOR stands for For, Let, Where, Order by, Return; and the clauses must be used in that order.

Questions for Thought and Discussion

How does XQuery compare with XSLT? Can we do basically the same things with both languages, or is one more powerful than the other? Can we do things more easily with one or the other? Which things? Why do we have both?

How does XQuery compare with SQL?


  1. Version history:
    • Version 1.1, 2012 Apr 6. Added examples PDF file.
    • Version 1.0, 2012 Apr 5. Added commentary.
    • Version 0.2, 2011 Apr 26. Added examples, without commentary.
    • Version 0.1, 2011 Apr 25. Initial draft, very bare.