A Simple XQuery Example


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

image from book
      <?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> 
image from book

The root element of this XML document is <Products>, which contains an arbitrary number of <Product> elements. Each <Product> element, in turn, contains <ProductID>, <Name>, and <ProductNumber> elements. In addition, the <Product> element also contains a Category attribute.

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 names that are of type “Socks”, you could use the following XQuery:

      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 preceding contents of the Products.xml file, the output of this query would be as follows:

      <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.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net