Chapter 6. Document Query

Table of Contents

6.1. XQuery output in HTML
6.1.1. Table
6.1.2. Computing New Information
6.1.3. Bulleted Lists
6.2. Transformation into a Compact Textual Form with XQuery
6.3. Querying an instance file
6.4. Additional Information on XQuery

In the previous chapter, we described how to transform an XML file into another by means of tree tranformations defined by templates. We have also seen how to extract information from an XML file. But now that XML files are used for keeping data similarly to databases, an alternate way of querying XML information has been defined, resulting in a language close to the well-known SQL.

It is called XQuery and is aimed at selecting information from XML databases that are often too large to be stored in a single XML file for which a random access would not necessarily be efficient. XQuery can also easily combine information from many XML documents, which is a bit awkward to do in XSLT. The output of an XQuery query is a sequence of XML nodes that lend themselves to the full power of XPath functions and XML constructors in order to further convert them into other XML nodes.

For the simple use cases we have shown in the previous chapter, transforming an XML document into an XHTML one by means of XSLT templates can also be seen as querying an input document to select some information which is then inserted into an XHTML template. This chapter illustrates some simple uses of XQuery to solve the problems shown previously.

Contrarily to XML Schema and XSLT, XQuery is not a fully XML based notation. Some readers might find it less verbose or rebarbative than XSLT. Relax NG Compact notation is also a non-XML-based notation for schemas of XML files when compared to XML Schema.

An XQuery program is called a query. It is an expression that selects or constructs a sequence of XML nodes. A query can take one of the following forms:

A query is often preceded by a "prolog" composed of declarations separated by a semicolon. For example, in the previous examples, the query should have been preceded by

declare namespace cat = "";

in order to define the cat namespace prefix used in the query. Declarations can also used to define variables, functions and other options to control the processing of the query. Most often the prolog is much longer that the query itself as there can be only one query in a file. This is not really a limitation because multiple queries can be merged into a single one: one only needs to create a sequence of queries by separating them with commas.

For complete details on the syntax of a query, see EBNF grammar of XQuery.

[1] pronounced flower even though the letters are not in the proper order...