|  | Home · All Classes · Main Classes · Grouped Classes · Modules · Functions |

# A Short Path to XQuery

XQuery is a language for querying XML data or non-XML data that can be modeled as XML. XQuery is specified by the W3C.

- Introduction
- Using Path Expressions To Match & Select Items

- Axis Steps
- Axis Specifiers
- Node Tests
- Shorthand Form
- Name Tests

- Wildcards in Name Tests

- Using Predicates In Path Expressions

- Positional Predicates
- Boolean Predicates

- Constructing Elements

- Constructing Values
- Node Constructors are Expressions

- Running The Cookbook Examples

- cookbook.xml

- Further Reading

## Introduction

Where Java and C++ are statement-based languages, the XQuery language is expression-based. The simplest XQuery expression is an XML element constructor:

     <recipe/>

This `<recipe/>` element is an XQuery expression that forms a complete XQuery. In fact, this XQuery doesn't actually query anything. It just creates an empty `<recipe/>` element in the output. But constructing new elements in an XQuery is often necessary.

An XQuery expression can also be enclosed in curly braces and embedded in another XQuery expression. This XQuery has a document expression embedded in a node expression:

      <html xmlns="http://www.w3.org/1999/xhtml/"
            xml:id="{doc("other.html")/html/@xml:id}"/>

It creates a new `html` element in the output and sets its `id` attribute to be the `id` attribute from an `html` element in the `other.html` file.

## Using Path Expressions To Match & Select Items

In C++ and Java, we write nested `for` loops and recursive functions to traverse XML trees in search of elements of interest. In XQuery, we write these iterative and recursive algorithms with path expressions.

A path expression looks somewhat like a typical file pathname for locating a file in a hierarchical file system. It is a sequence of one or more steps separated by slash '/' or double slash '//'. Although path expressions are used for traversing XML trees, not file systems, in QtXmlPatterms we can model a file system to look like an XML tree, so in QtXmlPatterns we can use XQuery to traverse a file system. See the file system example.

Think of a path expression as an algorithm for traversing an XML tree to find and collect items of interest. This algorithm is evaluated by evaluating each step moving from left to right through the sequence. A step is evaluated with a set of input items (nodes and atomic values), sometimes called the focus. The step is evaluated for each item in the focus. These evaluations produce a new set of items, called the result, which then becomes the focus that is passed to the next step. Evaluation of the final step produces the final result, which is the result of the XQuery. The items in the result set are presented in document order and without duplicates.

With QtXmlPatterns, a standard way to present the initial focus to a query is to call QXmlQuery::setFocus(). Another common way is to let the XQuery itself create the initial focus by using the first step of the path expression to call the XQuery `doc()` function. The `doc()` function loads an XML document and returns the document node. Note that the document node is not the same as the document element. The document node is a node constructed in memory, when the document is loaded. It represents the entire XML document, not the document element. The document element is the single, top-level XML element in the file. The `doc()` function returns the document node, which becomes the singleton node in the initial focus set. The document node will have one child node, and that child node will represent the document element. Consider the following XQuery:

     doc('cookbook.xml')//recipe

The `doc()` function loads the file cookbook.xml and returns the document node. The document node then becomes the focus for the next step `recipe`. Here the double slash means select all `recipe` elements found below the document node, regardless of where they appear in the document tree. The query selects all `recipe` elements in the cookbook. See Running The Cookbook Examples for instructions on how to run this query (and most of the ones that follow) from the command line.

Conceptually, evaluation of the steps of a path expression is similar to iterating through the same number of nested `for` loops. Consider the following XQuery, which builds on the previous one:

     doc('cookbook.xml')//recipe/title

This XQuery is a single path expression composed of three steps. The first step creates the initial focus by calling the `doc()` function. We can paraphrase what the query engine does at each step:

1. for each node in the initial focus (the document node)...
2. for each descendant node that is a `recipe` element...
3. collect the child nodes that are `title` elements.

Again the double slash means select all the `recipe` elements in the document. The single slash before the `title` element means select only those `title` elements that are child elements of a `recipe` element (i.e. not grandchildren, etc). The XQuery evaluates to a final result set containing the `title` element of each `recipe` element in the cookbook.

### Axis Steps

The most common kind of path step is called an axis step, which tells the query engine which way to navigate from the context node, and which test to perform when it encounters nodes along the way. An axis step has two parts, an axis specifier, and a node test. Conceptually, evaluation of an axis step proceeds as follows: For each node in the focus set, the query engine navigates out from the node along the specified axis and applies the node test to each node it encounters. The nodes selected by the node test are collected in the result set, which becomes the focus set for the next step.

In the example XQuery above, the second and third steps are both axis steps. Both apply the `element(name)` node test to nodes encountered while traversing along some axis. But in this example, the two axis steps are written in a shorthand form, where the axis specifier and the node test are not written explicitly but are implied. XQueries are normally written in this shorthand form, but they can also be written in the longhand form. If we rewrite the XQuery in the longhand form, it looks like this:

     doc('cookbook.xml')/descendant-or-self::element(recipe)/child::element(title)

The two axis steps have been expanded. The first step (`//recipe`) has been rewritten as `/descendant-or-self::element(recipe)`, where `descendant-or-self::` is the axis specifier and `element(recipe)` is the node test. The second step (`title`) has been rewritten as `/child::element(title)`, where `child::` is the axis specifier and `element(title)` is the node test. The output of the expanded XQuery will be exactly the same as the output of the shorthand form.

To create an axis step, concatenate an axis specifier and a node test. The following sections list the axis specifiers and node tests that are available.

### Axis Specifiers

An axis specifier defines the direction you want the query engine to take, when it navigates away from the context node. QtXmlPatterns supports the following axes.

Axis Specifier | refers to the axis containing...
--- | ---
`self::` | the context node itself
`attribute::` | all attribute nodes of the context node
`child::` | all child nodes of the context node (not attributes)
`descendant::` | all descendants of the context node (children, grandchildren, etc)
`descendant-or-self::` | all nodes in `descendant` + `self`
`parent::` | the parent node of the context node, or empty if there is no parent
`ancestor::` | all ancestors of the context node (parent, grandparent, etc)
`ancestor-or-self::` | all nodes in `ancestor` + `self`
`following::` | all nodes in the tree containing the context node, not including `descendant`, and that follow the context node in the document
`preceding::` | all nodes in the tree contianing the context node, not including `ancestor`, and that precede the context node in the document
`following-sibling::` | all children of the context node's `parent` that follow the context node in the document
`preceding-sibling::` | all children of the context node's `parent` that precede the context node in the document

### Node Tests

A node test is a conditional expression that must be true for a node if the node is to be selected by the axis step. The conditional expression can test just the kind of node, or it can test the kind of node and the name of the node. The XQuery specification for node tests also defines a third condition, the node's Schema Type, but schema type tests are not supported in QtXmlPatterns.

QtXmlPatterns supports the following node tests. The tests that have a `name` parameter test the node's name in addition to its kind and are often called the Name Tests.

Node Test | matches all...
--- | ---
`node()` | nodes of any kind
`text()` | text nodes
`comment()` | comment nodes
`element()` | element nodes (same as star: *)
`element(name)` | element nodes named `name`
`attribute()` | attribute nodes
`attribute(name)` | attribute nodes named `name`
`processing-instruction()` | processing-instructions
`processing-instruction(name)` | processing-instructions named `name`
`document-node()` | document nodes (there is only one)
`document-node(element(name))` | document node with document element `name`

### Shorthand Form

Writing axis steps using the longhand form with axis specifiers and node tests is semantically clear but syntactically verbose. The shorthand form is easy to learn and, once you learn it, just as easy to read. In the shorthand form, the axis specifier and node test are implied by the syntax. XQueries are normally written in the shorthand form. Here is a table of some frequently used shorthand forms:

Shorthand syntax | Short for... | matches all...
--- | --- | ---
`name` | `child::element(name)` | child nodes that are `name` elements
`*` | `child::element()` | child nodes that are elements (`node()` matches all child nodes)
`..` | `parent::node()` | parent nodes (there is only one)
`@*` | `attribute::attribute()` | attribute nodes
`@name` | `attribute::attribute(name)` | `name` attributes
`//` | `descendant-or-self::node()` | descendent nodes (when used instead of '/')

The XQuery language specification has a more detailed section on the shorthand form, which it calls the abbreviated syntax. More examples of path expressions written in the shorthand form are found there. There is also a section listing examples of path expressions written in the the longhand form.

### Name Tests

The name tests are the Node Tests that have the `name` parameter. A name test must match the node name in addition to the node kind. We have already seen name tests used:

     doc('cookbook.xml')//recipe/title

In this path expression, both `recipe` and `title` are name tests written in the shorthand form. XQuery resolves these names (QNames) to their expanded form using the namespace declarations it knows about. Resolving a name to its expanded form means replacing its namespace prefix (if one is present; there aren't any prefixes in the example) with a namespace URI. The expanded name then consists of the namespace URI and the local name.

But the names in the example above don't have namespace prefixes, because we didn't include a namespace declaration in our `cookbook.xml` file. Since we will often use XQuery to query XML documents that use namespaces, let's add a default namespace now. Change the document element in `cookbook.xml` from:

     <cookbook>

to...

     <cookbook xmlns="http://cookbook/namespace">

This is called a default namespace declaration because it doesn't include a namespace prefix. Including this default namespace declaration in the document element means that all unprefixed element names, including the document element itself (`cookbook`), are in the default namespace `http://cookbook/namespace`. Note that default namespace declarations do not apply to unprefixed attribute names. The unprefixed attribute names remain in no namespace. Also note that the URL we've chosen as our namespace URI need not refer to an actual location, and doesn't refer to one in this case. But click on http://www.w3.org/XML/1998/namespace, for example, which is the namespace URI for elements and attributes prefixed with `xml:`.

Now when we run the XQuery example above, no output is produced. The path expression no longer matches anything in the cookbook file because it doesn't know about the namespace we added to the cookbook. Apart from placing namespace declarations on element constructors, there are two ways to declare the namespace in the XQuery. We can give it a namespace prefix (e.g. `c` for cookbook) and prefix each name test with the namespace prefix:

     declare namespace c = "http://cookbook/namespace";
     doc('cookbook.xml')//c:recipe/c:title

Or we can declare the namespace to be the default element namespace, and then we can still run the original XQuery:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')//recipe/title

Both versions produce the same output. They both select all the `title` elements:

     <title xmlns="http://cookbook/namespace">Quick and Easy Mushroom Soup</title>
     <title xmlns="http://cookbook/namespace">Cheese on Toast</title>
     <title xmlns="http://cookbook/namespace">Hard-Boiled Eggs</title>

But note how the output is slightly different from the output produced before we added the namespace declaration to the cookbook file. QtXmlPatterns automatically includes the correct namespace attribute in each `title` element in the output. When QtXmlPatterns loads a document and expands a QName, it creates an instance of QXmlName, which retains the namespace prefix along with the namespace URI and the local name. See QXmlName for further details.

One thing to keep in mind from this namespace discussion, whether you run XQueries in a Qt program using QtXmlPatterns, or you run them from the command line using xmlpatterns, is that if you don't get the output you expect, it might be because you didn't declare the right namespaces in your XQuery.

#### Wildcards in Name Tests

The wildcard `'*'` can be used in a name test. To find all the attributes in the cookbook but select only the ones in the `xml` namespace, use the `xml:` namespace prefix but replace the local name (the attribute name) with the wildcard:

     doc('cookbook.xml')//@xml:*

Oops! If you save this XQuery in `file.xq` and run it through `xmlpatterns`, it doesn't work. You get an error message instead, something like this: Error SENR0001 in file:///...file.xq, at line 1, column 1: Attribute xml:id can't be serialized because it appears at the top level. The XQuery actually ran correctly. It selected a bunch of `xml:id` attributes and put them in the result set. But then `xmlpatterns` sent the result set to a serializer, which tried to output it as well-formed XML. Since the result set contains only attributes and attributes alone are not well-formed XML, the serializer reports a serialization error.

Fear not. XQuery can do more than just find and select elements and attributes. It can construct new ones on the fly as well, which is what we need to do here if we want `xmlpatterns` to let us see the attributes we selected. The example above and the ones below are revisited in the Constructing Elements section. You can jump ahead to see the modified examples now, and then come back, or you can press on from here.

To find all the `name` attributes in the cookbook and select them all regardless of their namespace, replace the namespace prefix with the wildcard and write `name` (the attribute name) as the local name:

     doc('cookbook.xml')//@*:name

To find and select all the attributes of the document element in the cookbook, replace the entire name test with the wildcard:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/@*

## Using Predicates In Path Expressions

Predicates can be used to further filter the nodes selected by a path expression. A predicate is an expression in square brackets ('[' and ']') that either returns a boolean value or a number. A predicate can appear at the end of any path step in a path expression. The predicate is applied to each node in the focus set. If a node passes the filter, the node is included in the result set. The query below selects the recipe element that has the `title` element `"Hard-Boiled Eggs"`.

     declare default element namespace "http://cookbook/namespace";
     doc("cookbook.xml")/cookbook/recipe[title = "Hard-Boiled Eggs"]

The dot expression ('.') can be used in predicates and path expressions to refer to the current context node. The following query uses the dot expression to refer to the current `method` element. The query selects the empty `method` elements from the cookbook.

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')//method[string-length(.) = 0]

Note that passing the dot expression to the string-length() function is optional. When string-length() is called with no parameter, the context node is assumed:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')//method[string-length() = 0]

Actually, selecting an empty `method` element might not be very useful by itself. It doesn't tell you which recipe has the empty method:

     <method xmlns="http://cookbook/namespace"/>

What you probably want to see instead are the `recipe` elements that have empty `method` elements:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')//recipe[string-length(method) = 0]

The predicate uses the string-length() function to test the length of each `method` element in each `recipe` element found by the node test. If a method contains no text, the predicate evaluates to `true` and the `recipe` element is selected. If the method contains some text, the predicate evaluates to `false`, and the `recipe` element is discarded. The output is the entire recipe that has no instructions for preparation:

     <recipe xmlns="http://cookbook/namespace" xml:id="HardBoiledEggs">
         <title>Hard-Boiled Eggs</title>
         <ingredient name="Eggs" quantity="3" unit="eggs"/>
         <time quantity="3" unit="minutes"/>
         <method/>
     </recipe>

The astute reader will have noticed that this use of `string-length()` to find an empty element is unreliable. It works in this case, because the method element is written as `<method/>`, guaranteeing that its string length will be 0. It will still work if the method element is written as `<method></method>`, but it will fail if there is any whitespace between the opening and ending `method` tags. A more robust way to find the recipes with empty methods is presented in the section on Boolean Predicates.

There are many more functions and operators defined for XQuery and XPath. They are all documented here.

### Positional Predicates

Predicates are often used to filter items based on their position in a sequence. For path expressions processing items loaded from XML documents, the normal sequence is document order. This query returns the second `recipe` element in the `cookbook.xml` file:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[2]

The other frequently used positional function is last(), which returns the numeric position of the last item in the focus set. Stated another way, last() returns the size of the focus set. This query returns the last recipe in the cookbook:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[last()]

And this query returns the next to last `recipe`:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[last() - 1]

### Boolean Predicates

The other kind of predicate evaluates to true or false. A boolean predicate takes the value of its expression and determines its effective boolean value according to the following rules:

- An expression that evaluates to a single node is `true`.
- An expression that evaluates to a string is `false` if the string is empty and `true` if the string is not empty.
- An expression that evaluates to a boolean value (i.e. type `xs:boolean`) is that value.
- If the expression evaluates to anything else, it's an error (e.g. type `xs:date`).

We have already seen some boolean predicates in use. Earlier, we saw a not so robust way to find the recipes that have no instructions. `[string-length(method) = 0]` is a boolean predicate that would fail in the example if the empty method element was written with both opening and closing tags and there was whitespace between the tags. Here is a more robust way that uses a different boolean predicate.

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[method[empty(step)]]

This one uses the empty() and function to test whether the method contains any steps. If the method contains no steps, then `empty(step)` will return `true`, and hence the predicate will evaluate to `true`.

But even that version isn't foolproof. Suppose the method does contain steps, but all the steps themselves are empty. That's still a case of a recipe with no instructions that won't be detected. There is a better way:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[not(normalize-space(method))]

This version uses the not and normalize-space() functions. `normalize-space(method))` returns the contents of the method element as a string, but with all the whitespace normalized, i.e., the string value of each `step` element will have its whitespace normalized, and then all the normalized step values will be concatenated. If that string is empty, then `not()` returns `true` and the predicate is `true`.

We can also use the position() function in a comparison to inspect positions with conditional logic. The position() function returns the position index of the current context item in the sequence of items:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[position() = 2]

Note that the first position in the sequence is position 1, not 0. We can also select all the recipes after the first one:

     declare default element namespace "http://cookbook/namespace";
     doc('cookbook.xml')/cookbook/recipe[position() > 1]

## Constructing Elements

In the section about using wildcards in name tests, we saw three simple example XQueries, each of which selected a different list of XML attributes from the cookbook. We couldn't use `xmlpatterns` to run these queries, however, because `xmlpatterns` sends the XQuery results to a serializer, which expects to serialize the results as well-formed XML. Since a list of XML attributes by itself is not well-formed XML, the serializer reported an error for each XQuery.

Since an attribute must appear in an element, for each attribute in the result set, we must create an XML element. We can do that using a `for` clause with a bound variable, and a `return` clause with an element constructor:

     for $i in doc("cookbook.xml")//@xml:*
     return <p>{$i}</p>

The `for` clause produces a sequence of attribute nodes from the result of the path expression. Each attribute node in the sequence is bound to the variable `$i`. The `return` clause then constructs a `p` element around the attribute node. Here is the output:

     <p xml:id="MushroomSoup"/>
     <p xml:id="CheeseOnToast"/>
     <p xml:id="HardBoiledEggs"/>

The output contains one `p` element for each `xml:id` attribute in the cookbook. Note that XQuery puts each attribute in the right place in its `p` element, despite the fact that in the `return` clause, the `$i` variable is positioned as if it is meant to become `p` element content.

The other two examples from the wildcard section can be rewritten the same way. Here is the XQuery that selects all the `name` attributes, regardless of namespace:

     for $i in doc("cookbook.xml")//@*:name
     return <p>{$i}</p>

And here is its output:

     <p name="Fresh mushrooms"/>
     <p name="Garlic"/>
     <p name="Olive oil"/>
     <p name="Milk"/>
     <p name="Water"/>
     <p name="Cream"/>
     <p name="Vegetable soup cube"/>
     <p name="Ground black pepper"/>
     <p name="Dried parsley"/>
     <p name="Bread"/>
     <p name="Cheese"/>
     <p name="Eggs"/>

And here is the XQuery that selects all the attributes from the document element:

     declare default element namespace "http://cookbook/namespace";
     for $i in doc("cookbook.xml")/cookbook/@*
     return <p>{$i}</p>

And here is its output:

     <p xmlns="http://cookbook/namespace" count="3"/>

### Constructing Values

To construct a value inside an element, enclose an expression in curly braces and embed it in the constructor. Here we compute the content for a new `e` element:

     <e>{sum((1, 2, 3))}</e>

Sending this XQuery through xmlpatterns produces:

     <e>6</e>

To compute the value of an attribute, enclose the expression in curly braces and embed it in the attribute value:

     declare variable $insertion := "example";
     <p class="important {$insertion} obsolete"/>

Sending this XQuery through xmlpatterns produces:

     <p class="important example obsolete"/>

### Node Constructors are Expressions

Because node constructors are expressions, they can be used in XQueries wherever expressions are allowed.

     declare default element namespace "http://cookbook/namespace";
     let $docURI := 'cookbook.xml'
     return if(doc-available($docURI))
            then doc($docURI)//recipe/<resept>{./node()}</resept>
            else <resept>Failed to load {$docURI}</resept>

If `cookbook.xml` is loaded without error, a `resept` element (Norweigian word for recipe) is constructed for each `recipe` element in the cookbook, and the child nodes of the `recipe` are copied into the `resept` element. But if the cookbook document doesn't exist or does not contain well-formed XML, a single `resept` element is constructed containing an error message.

## Running The Cookbook Examples

Most of the XQuery examples in this document refer to the cookbook written in XML shown below. Save it as `cookbook.xml`. In the same directory, save one of the cookbook XQuery examples in a `.xq` file (e.g. `file.xq`). Run the XQuery using Qt's command line utility:

     xmlpatterns file.xq

### cookbook.xml

     <?xml version="1.0" encoding="UTF-8"?>
     <cookbook>
         <recipe xml:id="MushroomSoup">
             <title>Quick and Easy Mushroom Soup</title>
             <ingredient name="Fresh mushrooms"
                         quantity="7"
                         unit="pieces"/>
             <ingredient name="Garlic"
                         quantity="1"
                         unit="cloves"/>
             <ingredient name="Olive oil"
                         quantity="2"
                         unit="tablespoons"/>
             <ingredient name="Milk"
                         quantity="200"
                         unit="milliliters"/>
             <ingredient name="Water"
                         quantity="200"
                         unit="milliliters"/>
             <ingredient name="Cream"
                         quantity="100"
                         unit="milliliters"/>
             <ingredient name="Vegetable soup cube"
                         quantity="1/2"
                         unit="cubes"/>
             <ingredient name="Ground black pepper"
                         quantity="1/2"
                         unit="teaspoons"/>
             <ingredient name="Dried parsley"
                         quantity="1"
                         unit="teaspoons"/>
             <time quantity="20"
                   unit="minutes"/>
             <method>
                 <step>1. Slice mushrooms and garlic.</step>
                 <step>2. Fry mushroom slices and garlic with olive oil.</step>
                 <step>3. Once mushrooms are cooked, add milk, cream water. Stir.</step>
                 <step>4. Add vegetable soup cube.</step>
                 <step>5. Reduce heat, add pepper and parsley.</step>
                 <step>6. Turn off the stove before the mixture boils.</step>
                 <step>7. Blend the mixture.</step>
             </method>
         </recipe>
         <recipe xml:id="CheeseOnToast">
             <title>Cheese on Toast</title>
             <ingredient name="Bread"
                         quantity="2"
                         unit="slices"/>
             <ingredient name="Cheese"
                         quantity="2"
                         unit="slices"/>
             <time quantity="3"
                   unit="minutes"/>
             <method>
                 <step>1. Slice the bread and cheese.</step>
                 <step>2. Grill one side of each slice of bread.</step>
                 <step>3. Turn over the bread and place a slice of cheese on each piece.</step>
                 <step>4. Grill until the cheese has started to melt.</step>
                 <step>5. Serve and enjoy!</step>
             </method>
         </recipe>
         <recipe xml:id="HardBoiledEggs">
             <title>Hard-Boiled Eggs</title>
             <ingredient name="Eggs"
                         quantity="3"
                         unit="eggs"/>
             <time quantity="3"
                   unit="minutes"/>
             <method/>
         </recipe>
     </cookbook>

## Further Reading

There is much more to the XQuery language than we have presented in this short introduction. We will be adding more here in later releases. In the meantime, playing with the `xmlpatterns` utility and making modifications to the XQuery examples provided here will be quite informative. An XQuery textbook will be a good investment.

You can also ask questions on XQuery mail lists:

- qt-interest
- talk at x-query.com.

FunctX has a collection of XQuery functions that can be both useful and educational.

This introduction contains many links to the specifications, which, of course, are the ultimate source of information about XQuery. They can be a bit difficult, though, so consider investing in a textbook:

- XQuery 1.0: An XML Query Language - the main source for syntax and semantics.
- XQuery 1.0 and XPath 2.0 Functions and Operators - the builtin functions and operators.