XQuery was devised primarily as a query language for data stored in XML form. So its main role is to get information out of XML databases.
Here's an XQuery that simply retrieves and displays the whole document:
doc('http://www.stylusstudio.com/examples/videos.xml')
The file contains a number of sections. One of them is an <actors> element, which we can select like this:
.//actors
This produces the result:
<actors>
<actor id="00000015">Anderson, Jeff</actor>
<actor id="00000030">Bishop, Kevin</actor>
<actor id="0000000f">Bonet, Lisa</actor>
...etc...
</actors>
A little more complex:
.//actors/actor[ends-with(., 'Lisa')]
gives the output:
<actor id="0000000f">Bonet, Lisa</actor>
<actor id="0000001b">Spoonhauer, Lisa</actor>
This XPath expression has two parts: a path .//actors/actor that indicates which elements we are interested in, and a predicate [endswith(., 'Lisa')] that indicates a test that the nodes must satisfy.
Let's suppose we want to find the titles of all the videos featuring an actor whose first name is Lisa:
//video[actorRef=//actors/actor[ends-with(., 'Lisa')]/@id]/title
XQuery FLWOR Expressions
XQuery allows you to write join queries in a similar way to the familiar SQL approach. Its equivalent of SQL's SELECT expression is called the FLWOR expression, named after its five clauses: for, let, where, order by, return.
Here's the previous example, rewritten this time as a FLWOR expression (and ordered by release date):
let $doc := .
for $v in $doc//video,
$a in $doc//actors/actor
where ends-with($a, 'Lisa')
and $v/actorRef = $a/@id
order by $v/year
return $v/title
If you've got a real database, the form of the queries won't need to change all that much from these examples. Instead of using the doc() function (or simply ".") to select a document, you're likely to call the collection() function to open a database, or a specific collection of documents within a database.
Examples by Michael Kay/Stylusstudio.