colleague of mine, a database programmer who had spent some time working with an early XQuery implementation, once referred to the language as the smiley language. When I asked whether that had to do with the simplicity of the language, he replied in Hungarian-accented English, "Oh, no, the language itself is a bear, but they made the comment delimiters into smileys (: :) to make you smile even as your database gets thrashed."
While not exactly a ringing indictment of the language, his comments served to highlight the fact that while XQuery has a structure similar to most languages have, the differences can trip you up dramatically. XQuery is not a hard language to learn, but it can be a language that makes you try to understand why it’s not working.
Xquery's control structures have been given the rather quaint acronym of FLOWR, shorthand for the most critical
(but not the only) XQuery structures used by the language. FLOWR itself stands for five operations:
- Order by
Four of which have analogs in SQL:
- ORDER BY
These terms are used to either assign or retrieve items from a set.
XQuery is a set manipulation language. It's whole purpose is to work with sets of information, not just
single scalar values. Additionally, as a set manipulation language, it is meant to augment—rather than replace—the XPath 2.0 language that's built into the specification. Indeed, in essence, most of XQuery is just a means to wrap a control language around XPath, in a manner somewhat similar to the way that XSLT combines a templating language with XPath.
For this reason, when you are working with XQuery, the most effective use of the language is to do as much as possible within XPath 2 first, then go to the XQuery command structures when you've reached a point where XPath 2 can't quite get you all the way.
For example, suppose that you had an XML data source that consisted of a collection of employment records. For now,
assume they are in the file employees.xml (see Listing 1).
The for statement provides a way of setting the context to each employee in turn. The following code shows a simple XQuery script that outputs each employee in the order encountered in a list:
for $employee in doc("employees.xml")/employees/employee
In this case, a sequence of employee elements with their corresponding bodies is returned. Of course, the exact rendering of this sequence depends on the particular XQuery implementation used. For instance, if you use Saxon 9's XQuery engine, the output would look something like