The Relation to XPath
If you are familiar with XPath, you'll recognize the syntax of the XQuery we just executed. That's because XQuery is built on XPath. XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators. As a matter of fact, every XPath expression is a valid XQuery. This is good news because if you have already learned and used XPath, it won't take much additional study to master XQuery.
FLWOR, an acronym for "For, Let, Where, Order by, Return," describes a type of expression used in XQuery that is similar to the "SELECT FROM WHERE ORDER BY" you know from SQL. Here is a description of the FLWOR clauses:
- for iterates over the result of an expression and binds a variable to each item returned by the expression.
- let binds a variable to the result of an expression.
- where filters the tuples of variable bindings that are generated by the for and let clauses.
- order by specifies the order in which values are processed by the return clause.
- return evaluates the expression in the clause once for each tuple of bound variables that is generated by the for, let, where, and order by clauses and concatenates the results of all the evaluations into a single sequence, which becomes the result of the FLWOR expression.
The practice of placing frequently used segments of code into functions is common to all programming languages. XQuery is no different. We have already mentioned that XQuery supports the same functions as XPath. There are over 100 built-in functions (for a summary, see www.w3schools.com/xpath/xpath_functions .asp). You can also write your own functions. XQuery functions exist within a namespace. Each function name consists of a prefix that is a shortcut to the namespace followed by a colon followed by the function name. The default prefix, which you can see in the list of built-in functions, is fn:. For user-written functions, you can use the prefix local:.
A function that uses a FLWOR expression to perform the equivalent of the join with which you are familiar from SQL is printBandMemberInstrument (available online). It joins musicians.xml, which we have already seen, and band.xml (which is also available online). Notice that the return clause can contain XML tags as well as data.
XQuery provides the same power and flexibility for XML as SQL does for relational data. XQuery also makes it possible for you to query office documentsspreadsheets, word-processing documents, and the like. For more details, see Marc Van Cappellen's article "XQuery Your Office Documents" (www.ddj.com/linux-open-source/202401913).