|
Depending on the nature of the data you are searching, and the type of query expression you need to build, you can choose from one of several available expression formats. These include:
|
| • | FLWR (pronounced “flower”), which provides a series of keywords that are comparable to those used by SQL. |
| • | Path expressions, which allow you to access elements and attributes of an input document. |
| • | Element constructors that enable the dynamic creation of new XML elements and values. |
| • | Conditional expressions that can add complex logic to query statements using the well-known if-then-else construct. |
| • | Quantified expressions that allow for the inclusion of quantifying logic. Using keywords, such as some and every, submitted test expressions result in either “false” or “true”. |
|
|
For our example we’ll be building a FLWR query expression using the for, where and return keywords.
The for clause below provides a variable that is bound to the book element of the books.xml document. The values that will be output are defined by the subsequent XQuery clauses.
|
|
for $x in document("books.xml")//book
|
|
The where fragment is very similar to the SQL WHERE clause, in that it defines the search criteria. In this case, we are searching for all books written by “Joe Smith”.
|
|
where $x/author = "Joe Smith"
|
|
In order to define what data from the queried XML tree we actually want returned, XQuery provides the return keyword (much like an SQL SELECT statement). In response to our query, we’d like to get the titles written by Joe Smith.
|
|
return $x/title
|
|
When the following XQuery statement:
|
|
for $x in document("books.xml")//book
where $x/author = "Joe Smith"
return $x/title
|
|
… queries this document:
|
<inventory>
<book category=”Fiction”>
<title>Joy of Integration</title>
<author>Joe Smith</author>
</book>
<book category=”Non-Fiction”>
<title>Integration for Dummies</title>
<author>John Doe</author>
</book>
</inventory>
|
|
…it returns the following result:
|
|
<title>Joy of Integration</title>
|
With numerous types of expressions at its disposal, the XQuery specification can be used to create complex query logic. Key features to look out for include support for XSD data types, XPath functions, SQL aggregation functions, and many other SQL features, such as grouping, joins and sorting.
|