Element Construction

We've seen how to perform operations on data, use path expressions to select data, and iterate over data. Now we look at how to construct data. The simplest way to construct data is to include literal XML data in a query. Here is an example:

 <article id="1001">   <name>Red Bicycle</name>   <seller idref="U01"/>   <start_date>1999-01-05</start_date>   <end_date>1999-01-20</end_date>   <reserve_price>40</reserve_price> </article> 

has type element(article) .

The type of this expression is the type declared for the article element in Listing 4.2. This type states that the element has one attribute (an id of type xs:ID ), and five elements (including start_date and end_date , both of type xs:date ). At evaluation time, the element is constructed and then validated . This ensures that the element itself and all the attributes and elements within it are labeled with the correct type. The validation implicit in element construction depends on a mode and context specified by the static environment; details of controlling validations are discussed in the next section.

One may also include computed data within a constructor. The function in Listing 4.9 takes an article that has failed to sell and yields a new article with new dates and a reduced reserve price:

Listing 4.9 Using Computed Data in a Constructor: Definition of the bargain Function
 define function bargain($a as element(article)) as element(article) {     <article>{       $a/@id,       $a/name,       $a/seller,       <start_date>{ fn:current-date() }</start_date>       <end_date> { fn:current-date() + ($a/end_date - $a/start_date)                                                           }</end_date>       <reserve_price>{ $a/reserve_price * 0.80 }</reserve_price>     }</article> } 

This function definition is well typed, because the type of the function's body matches the return type, element(article) .

The real value of the type system is for detecting errors. Here is a variant of the bargain function that contains several type errors:

 define function bargain($a as element(article)) as element(article) {     <article>{       $a/name,       $a/seller,       <start_date>{ fn:current-date() }</start_date>       <end_date> { $a/end_date - $a/start_date }</end_date>       <reserve_price>{ $a/reserve_price * 0.80 }</reserve_price>     }</article> } 

Now the type system detects two errors. First, an article element is required to contain an id attribute, but none appears in the above constructor expression. Second, the type expected for the end_date element is xs:date , but the type of the expression $a/end_date - $a/start_date is xs:dayTimeDuration .



XQuery from the Experts(c) A Guide to the W3C XML Query Language
Beginning ASP.NET Databases Using VB.NET
ISBN: N/A
EAN: 2147483647
Year: 2005
Pages: 102

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