XQuery is used to query an XML document, and for that you need an XML document to talk about while examining the various queries. For the purposes of this chapter, consider the XML document in Listing 10-1, which describes the structure of a set of products.
Listing 10-1: Sample XML file
|
|
<?xml version="1.0" encoding="utf-8"?> <Products> <Product Category="Helmets"> <ProductID>707</ProductID> <Name>Sport-100 Helmet, Red</Name> <ProductNumber>HL-U509-R</ProductNumber> </Product> <Product Category="Socks"> <ProductID>709</ProductID> <Name>Mountain Bike Socks, M</Name> <ProductNumber>SO-B909-M</ProductNumber> </Product> <Product Category="Socks"> <ProductID>710</ProductID> <Name>Mountain Bike Socks, L</Name> <ProductNumber>SO-B909-L</ProductNumber></Product> <Product Category="Caps"> <ProductID>712</ProductID> <Name>AWC Logo Cap</Name > <ProductNumber>CA-1098</ProductNumber> </Product> </Products>
|
|
The root element of this XML document is
<Products>
, which contains an arbitrary number of
<Product>
elements. Each
<Product>
element, in
Just as SQL needs to be able to access any row or column in a relational table, XQuery needs to be able to access any node in an XML document. XML structures have both hierarchy and sequence, and can contain complex structure. Path expressions directly support hierarchy and sequence, and allow you to navigate any XML structure. In its simplest form, an XQuery can simply be an XPath expression. For example, to get a list of all of the product
doc("Products.xml")/Products/Product[@Category="Socks"]/Name
The
doc(“Products.xml”)
part indicates the XML data store, which is an XML file named
Products.xml
in this case. Given the
<Name>Mountain Bike Socks, M</Name> <Name>Mountain Bike Socks, L</Name>
The output of an XQuery statement is a collection of XML elements. In the previous example, it is a collection of <Name> elements.
In literal XML constructors, you can use curly braces
({})
to add content that is computed when the query is run. This is called an enclosed expression. For example, in the previous example, if you want all of the
<
<ProductNames> { doc("Products.xml")/Products/Product[@Category="Socks"]//Name } </ProductNames>
With this addition, the output would be as
<ProductNames> <Name>Mountain Bike Socks, M</Name> <Name>Mountain Bike Socks, L</Name> </ProductNames>
Note that in this query, you used curly braces around the XPath expression within the <ProductNames> element. The braces denote that the content within the braces is an XQuery expression, and not literal content. For example, the following query omits the braces:
<ProductNames> doc("Products.xml")/Products/Product[@Category="Socks"]//Name </ProductNames>
The output of this query would be as follows:
<ProductNames> doc("Products.xml")/Products/Product[@Category="Socks"]//Name </ProductNames>