The presentation of this document has been augmented to identify changes from a previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text.


W3C

XML Query Use Cases

W3C Working Draft 8 June 2006

This version:
Latest version:
Previous version:
Editors:
Don Chamberlin, IBM Almaden Research Center
Peter Fankhauser, Infonyte GmbH
Daniela Florescu, Oracle corporation
Massimo Marchiori, University of Venice
Jonathan Robie, DataDirect Technologies

This document is also available in these non-normative formats:

XML
.


Abstract

This document specifies usage scenarios for XQuery.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This version of the Use Cases document corresponds to the XQuery Working Draft released on 8 June 2006. The queries in this document have been parsed using a parser generated from the same grammar used to create the documentation for the XQuery Working Draft.

This is a public W3C Working Draft for review by W3C Members and other interested parties. Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document wasproduced bythe XML Query Working Group(WG) (part ofthe XMLActivity). Thisdocument was produced jointly by the XML Query Working Group and the XSL Working Group, both of which arepart of the XML Activity.

Comments on thisdocument are invited and should bemade in W3C's publicBugzilla system (instructionscan be found at http://www.w3.org/XML/2005/04/qt-bugzilla). If accessto that system is not feasible,you may send your comments to the W3C XSLT/XPath/XQuery mailing list, public-qt-comments@w3.org. It willbe very helpful if you includethe string [XQueryUseCases] inthe subject line of your comment, whethermade in Bugzilla or in email. EachBugzilla entry and email message should contain only one comment. Archivesof thecomments and responses are available athttp://lists.w3.org/Archives/Public/public-qt-comments/ .

This document was produced by a group operatingunder the 5February 2004W3C Patent Policy.This documentis informativeonly.W3C maintainsa public listof any patent disclosuresmade in connection withthedeliverables ofthe group; that page alsoincludes instructions fordisclosing a patent. An individual whohas actual knowledgeof a patent whichthe individual believes contains Essential Claim(s)must disclose the information inaccordance with section 6of the W3C PatentPolicy.

Table of Contents

1 Use Cases for XML Queries
    1.1 Use Case "XMP": Experiences and Exemplars
        1.1.1 Document Type Definitions (DTD)
        1.1.2 Sample Data
        1.1.3 DTD for Q5
        1.1.4 Sample Data for Q5
        1.1.5 DTD for Q9
        1.1.6 Data for Q9
        1.1.7 DTD for Q10
        1.1.8 Data for Q10
        1.1.9 Queries and Results
            1.1.9.1 Q1
            1.1.9.2 Q2
            1.1.9.3 Q3
            1.1.9.4 Q4
            1.1.9.5 Q5
            1.1.9.6 Q6
            1.1.9.7 Q7
            1.1.9.8 Q8
            1.1.9.9 Q9
            1.1.9.10 Q10
            1.1.9.11 Q11
            1.1.9.12 Q12
    1.2 Use Case "TREE": Queries that preserve hierarchy
        1.2.1 Description
        1.2.2 Document Type Definition (DTD)
        1.2.3 Sample Data
        1.2.4 Queries and Results
            1.2.4.1 Q1
            1.2.4.2 Q2
            1.2.4.3 Q3
            1.2.4.4 Q4
            1.2.4.5 Q5
            1.2.4.6 Q6
    1.3 Use Case "SEQ" - Queries based on Sequence
        1.3.1 Description
        1.3.2 Document Type Definition (DTD)
        1.3.3 Sample Data
        1.3.4 Queries and Results
            1.3.4.1 Q1
            1.3.4.2 Q2
            1.3.4.3 Q3
            1.3.4.4 Q4
            1.3.4.5 Q5
    1.4 Use Case "R" - Access to Relational Data
        1.4.1 Description
        1.4.2 Document Type Definition (DTD)
        1.4.3 Sample Data
        1.4.4 Queries and Results
            1.4.4.1 Q1
            1.4.4.2 Q2
            1.4.4.3 Q3
            1.4.4.4 Q4
            1.4.4.5 Q5
            1.4.4.6 Q6
            1.4.4.7 Q7
            1.4.4.8 Q8
            1.4.4.9 Q9
            1.4.4.10 Q10
            1.4.4.11 Q11
            1.4.4.12 Q12
            1.4.4.13 Q13
            1.4.4.14 Q14
            1.4.4.15 Q15
            1.4.4.16 Q16
            1.4.4.17 Q17
            1.4.4.18 Q18
    1.5 Use Case "SGML": Standard Generalized Markup Language
        1.5.1 Description
        1.5.2 Document Type Definition (DTD)
        1.5.3 Sample Data
        1.5.4 Queries and Results
            1.5.4.1 Q1
            1.5.4.2 Q2
            1.5.4.3 Q3
            1.5.4.4 Q4
            1.5.4.5 Q5
            1.5.4.6 Q6
            1.5.4.7 Q7
            1.5.4.8 Q8a
            1.5.4.9 Q8b
            1.5.4.10 Q9
            1.5.4.11 Q10
    1.6 Use Case "STRING": String Search
        1.6.1 Description
        1.6.2 Document Type Definition (DTD)
        1.6.3 Sample Data
        1.6.4 Queries and Results
            1.6.4.1 Q1
            1.6.4.2 Q2
            1.6.4.3 Q3
            1.6.4.4 Q4
            1.6.4.5 Q5
    1.7 Use Case "NS" - Queries Using Namespaces
        1.7.1 Description
        1.7.2 Document Type Definition (DTD)
        1.7.3 Sample Data
        1.7.4 Queries and Results
            1.7.4.1 Q1
            1.7.4.2 Q2
            1.7.4.3 Q3
            1.7.4.4 Q4
            1.7.4.5 Q5
            1.7.4.6 Q6
            1.7.4.7 Q7
            1.7.4.8 Q8
    1.8 Use Case "PARTS" - Recursive Parts Explosion
        1.8.1 Description
        1.8.2 Document Type Definitions (DTD)
        1.8.3 Sample Data
        1.8.4 Queries and Results
            1.8.4.1 Q1
    1.9 Use Case "STRONG" - queries that exploit strongly typed data
        1.9.1 Description
        1.9.2 Schema
        1.9.3 Sample Data
        1.9.4 Queries
            1.9.4.1 Q1
            1.9.4.2 Q2
            1.9.4.3 Q3
            1.9.4.4 Q4
            1.9.4.5 Q5
            1.9.4.6 Q6
            1.9.4.7 Q7
            1.9.4.8 Q8
            1.9.4.9 Q9
            1.9.4.10 Q10
            1.9.4.11 Q11
            1.9.4.12 Q12

Appendices

A Acknowledgements
B Change Log (Non-Normative)
    B.1 8 May 2006
    B.2 31 Aug 2005
    B.3 11 July 2005
    B.4 04 April 2005
    B.5 30 Jan 2005
C References (Non-Normative)


1 Use Cases for XML Queries

The use cases listed below were created by the XML Query Working Group to illustrate important applications for an XML query language. Each use case is focused on a specific application area, and contains a Document Type Definition (DTD) and example input data. Each use case specifies a set of queries that might be applied to the input data, and the expected results for each query. Since the English description of each query is concise, the expected results form an important part of the definition of each query, specifying the expected output format. These use cases were originally published as part of the [XQuery Requirements] document, without solutions in concrete query languages. Now it is being republished with solutions for [XQuery]. These use cases are also being used by the W3C XML Query Testing Task Force.

The input environment for each use case is stated in its Document Type Definition (DTD) section. All of these use cases assume that input is provided in the form of one or more documents with specific names. For instance, the authors in a document may be accessed with expressions like this:

doc("http://bstore1.example.com/bib.xml")//author

Some implementations of XQuery bind input to external variables. If the environment has bound the external variable $b to the same document used in the above query, this expression would return the same set of authors:

$b//author

Some implementations of XQuery predefine a single 'context item', which is available at the root level of a query, and which is used to resolve paths that begin with a leading slash. In such an implementation, if the context item is bound to document node of the same well-formed document used in the previous examples, this expression would return the same set of authors:

//author

Previous versions of this document accessed implicit documents using the input() function, which no longer exists. The input() function had similar functionality to a predefined context item, except that it could be bound to a sequence of nodes, whereas the context item may only be bound to a single node. The use cases that used input() have been rewritten to use explicit file names.

Several implementors have asked that we make the queries from these use cases available in a separate file to make it easier for them to test their parsers. These queries may be found in [Use Case Sample Queries]. Also, the queries from the XQuery specification itself have been made available in [XQuery Sample Queries].

To make output more readable, the output of queries has been formatted using whitespace which may not be returned by a query processor. This whitespace should not be considered normative for the correctness of results.

These queries weretested with a dynamicimplementation of XQuery. Somequeries may require additional type declarations to be usedwith animplementation that implements the Static Typing feature.

1.1 Use Case "XMP": Experiences and Exemplars

This use case contains several example queries that illustrate requirements gathered from the database and document communities.

1.1.9 Queries and Results

1.2 Use Case "TREE": Queries that preserve hierarchy

Some XML document-types have a very flexible structure in which text is mixed with elements and many elements are optional. These document-types show a wide variation in structure from one document to another. In documents of these types, the ways in which elements are ordered and nested are usually quite important.

1.2.4 Queries and Results

1.3 Use Case "SEQ" - Queries based on Sequence

This use case illustrates queries based on the sequence in which elements appear in a document.

1.3.4 Queries and Results

1.3.4.5 Q5

In Report1, what happened between the first Incision and the second Incision?

Solution in XQuery:

Here is another solution that is perhaps more efficient and less readable:

Expected Result:

In the above output, the contents of the critical sequence element include a text node, an action element, and the text node containing the content of the action element. But the serialization we are using already shows all descendants of a given node. If $c is bound to a sequence of nodes, the following expression eliminates members of the sequence that are descendants of another node already found in the sequence:

In the following solution, the between() function takes a sequence of nodes, a starting node, and an ending node, and returns the nodes between them:

Here is the output from the above query:

1.4 Use Case "R" - Access to Relational Data

One important use of an XML query language will be to access data stored in relational databases. This use case describes one possible way in which this access might be accomplished.

1.4.3 Sample Data

Here is an abbreviated set of data showing the XML format of the instances:

The entire data set is represented by the following table:

USERS
USERIDNAMERATING
U01Tom JonesB
U02Mary DoeA
U03Dee LinquentD
U04Roger SmithC
U05Jack SpratB
U06Rip Van WinkleB
ITEMS
ITEMNODESCRIPTIONOFFERED_BYSTART_DATEEND_DATERESERVE_PRICE
1001Red BicycleU011999-01-051999-01-2040
1002MotorcycleU021999-02-111999-03-15500
1003Old BicycleU021999-01-101999-02-2025
1004TricycleU011999-02-251999-03-0815
1005Tennis RacketU031999-03-191999-04-3020
1006HelicopterU031999-05-051999-05-2550000
1007Racing BicycleU041999-01-201999-02-20200
1008Broken BicycleU011999-02-051999-03-0625
BIDS
USERIDITEMNOBIDBID_DATE
U021001351999-01-07
U041001401999-01-08
U021001451999-01-11
U041001501999-01-13
U021001551999-01-15
U0110024001999-02-14
U0210026001999-02-16
U0310028001999-02-17
U04100210001999-02-25
U02100212001999-03-02
U041003151999-01-22
U051003201999-02-03
U011004401999-03-05
U0310071751999-01-25
U0510072001999-02-08
U0410072251999-02-12

1.4.4 Queries and Results

1.4.4.5 Q5

For bicycle(s) offered by Tom Jones that have received a bid, list the item number, description, highest bid, and name of the highest bidder, ordered by item number.

Solution in XQuery:

The above query does several joins, and requires the results in a particular order. If there were no order by clause, results would be reported in document order. If you do not care about the order, you can use the unordered function to inform the query processor that the order of the lists in the for clause is not significant, which means that the tuples can be generated in any order. This can enable better optimization.

Unordered Solution in XQuery:

Expected Result:

1.5 Use Case "SGML": Standard Generalized Markup Language

1.5.3 Sample Data

The queries in this use case are based on the following sample data, which is found in the file "sgml.xml". Line numbers have been added to the data to allow the results of queries to be conveniently specified.

 0: <!DOCTYPE report SYSTEM "report.dtd">
 1: <report>
 2: <title>Getting started with SGML</title>
 3: <chapter>
 4: <title>The business challenge</title>
 5: <intro>
 6: <para>With the ever-changing and growing global market, companies and
 7: large organizations are searching for ways to become more viable and
 8: competitive. Downsizing and other cost-cutting measures demand more
 9: efficient use of corporate resources. One very important resource is
10: an organization's information.</para>
11: <para>As part of the move toward integrated information management,
12: whole industries are developing and implementing standards for
13: exchanging technical information. This report describes how one such
14: standard, the Standard Generalized Markup Language (SGML), works as
15: part of an overall information management strategy.</para>
16: <graphic graphname="infoflow"/></intro></chapter>
17: <chapter>
18: <title>Getting to know SGML</title>
19: <intro>
20: <para>While SGML is a fairly recent technology, the use of
21: <emph>markup</emph> in computer-generated documents has existed for a
22: while.</para></intro>
23: <section shorttitle="What is markup?">
24: <title>What is markup, or everything you always wanted to know about
25: document preparation but were afraid to ask?</title>
26: <intro>
27: <para>Markup is everything in a document that is not content. The
28: traditional meaning of markup is the manual <emph>marking</emph> up
29: of typewritten text to give instructions for a typesetter or
30: compositor about how to fit the text on a page and what typefaces to
31: use. This kind of markup is known as <emph>procedural markup</emph>.</para></intro>
32: <topic topicid="top1">
33: <title>Procedural markup</title>
34: <para>Most electronic publishing systems today use some form of
35: procedural markup. Procedural markup codes are good for one
36: presentation of the information.</para></topic>
37: <topic topicid="top2">
38: <title>Generic markup</title>
39: <para>Generic markup (also known as descriptive markup) describes the
40: <emph>purpose</emph> of the text in a document. A basic concept of
41: generic markup is that the content of a document must be separate from
42: the style. Generic markup allows for multiple presentations of the
43: information.</para></topic>
44: <topic topicid="top3">
45: <title>Drawbacks of procedural markup</title>
46: <para>Industries involved in technical documentation increasingly
47: prefer generic over procedural markup schemes. When a company changes
48: software or hardware systems, enormous data translation tasks arise,
49: often resulting in errors.</para></topic></section>
50: <section shorttitle="What is SGML?">
51: <title>What <emph>is</emph> SGML in the grand scheme of the universe, anyway?</title>
52: <intro>
53: <para>SGML defines a strict markup scheme with a syntax for defining
54: document data elements and an overall framework for marking up
55: documents.</para>
56: <para>SGML can describe and create documents that are not dependent on
57: any hardware, software, formatter, or operating system. Since SGML documents
58: conform to an international standard, they are portable.</para></intro></section>
59: <section shorttitle="How does SGML work?">
60: <title>How is SGML and would you recommend it to your grandmother?</title>
61: <intro>
62: <para>You can break a typical document into three layers: structure,
63: content, and style. SGML works by separating these three aspects and
64: deals mainly with the relationship between structure and content.</para></intro>
65: <topic topicid="top4">
66: <title>Structure</title>
67: <para>At the heart of an SGML application is a file called the DTD, or
68: Document Type Definition. The DTD sets up the structure of a document,
69: much like a database schema describes the types of information it
70: handles.</para>
71: <para>A database schema also defines the relationships between the
72: various types of data. Similarly, a DTD specifies <emph>rules</emph>
73: to help ensure documents have a consistent, logical structure.</para></topic>
74: <topic topicid="top5">
75: <title>Content</title>
76: <para>Content is the information itself. The method for identifying
77: the information and its meaning within this framework is called
78: <emph>tagging</emph>. Tagging must
79: conform to the rules established in the DTD (see <xref xrefid="top4"/>).</para>
80: <graphic graphname="tagexamp"/></topic>
81: <topic topicid="top6">
82: <title>Style</title>
83: <para>SGML does not standardize style or other processing methods for
84: information stored in SGML.</para></topic></section></chapter>
85: <chapter>
86: <title>Resources</title>
87: <section>
88: <title>Conferences, tutorials, and training</title>
89: <intro>
90: <para>The Graphic Communications Association has been
91: instrumental in the development of SGML. GCA provides conferences,
92: tutorials, newsletters, and publication sales for both members and
93: non-members.</para>
94: <para security="c">Exiled members of the former Soviet Union's secret
95: police, the KGB, have infiltrated the upper ranks of the GCA and are
96: planning the Final Revolution as soon as DSSSL is completed.</para>
97: </intro>
98: </section>
99: </chapter>
100:</report>
                    

1.5.4 Queries and Results

1.6 Use Case "STRING": String Search

1.6.3 Sample Data

The queries in this use case are based on the following input data, which is found in the file "string.xml".

<?xml version="1.0" encoding="ISO-8859-1"?>
<news>
<news_item>
   <title> Gorilla Corporation acquires YouNameItWeIntegrateIt.com </title>
   <content>
      <par> Today, Gorilla Corporation announced that it will purchase
          YouNameItWeIntegrateIt.com. The shares of
          YouNameItWeIntegrateIt.com dropped $3.00 as a result of this
          announcement.
      </par>

      <par> As a result of this acquisition, the CEO of
          YouNameItWeIntegrateIt.com Bill Smarts resigned. He did not
          announce what he will do next.  Sources close to
          YouNameItWeIntegrateIt.com hint that Bill Smarts might be
          taking a position in Foobar Corporation.
      </par>

      <par>YouNameItWeIntegrateIt.com is a leading systems integrator
          that enables <quote>brick and mortar</quote> companies to
          have a presence on the web.
      </par>

   </content>
   <date>1-20-2000</date>
   <author>Mark Davis</author>
   <news_agent>News Online</news_agent>
</news_item>

<news_item>
   <title>Foobar Corporation releases its new line of Foo products
   today</title>
   <content>
      <par> Foobar Corporation releases the 20.9 version of its Foo
            products.  The new version of Foo products solve known
            performance problems which existed in 20.8 line and
            increases the speed of Foo based products tenfold. It also
            allows wireless clients to be connected to the Foobar
            servers.
      </par>
      <par> The President of Foobar Corporation announced that they
            were proud to release 20.9 version of Foo products and
            they will upgrade existing customers <footnote>where
            service agreements exist</footnote>
            promptly. TheAppCompany Inc. immediately announced that it
            will release the new version of its products to utilize
            the 20.9 architecture within the next three months.
      </par>
      <figure>
          <title>Presidents of Foobar Corporation and TheAppCompany
          Inc. Shake Hands</title> <image source="handshake.jpg"/>
      </figure>
   </content>
   <date>1-20-2000</date>
   <news_agent>Foobar Corporation</news_agent>
</news_item>

<news_item> <title>Foobar Corporation is suing Gorilla Corporation for
   patent infringement </title>
   <content>
      <par> In surprising developments today, Foobar Corporation
         announced that it is suing Gorilla Corporation for patent
         infringement. The patents that were mentioned as part of the
         lawsuit are considered to be the basis of Foobar
         Corporation's <quote>Wireless Foo</quote> line of products.
      </par>
      <par>The tension between Foobar and Gorilla Corporations has
         been increasing ever since the Gorilla Corporation acquired
         more than 40 engineers who have left Foobar Corporation,
         TheAppCompany Inc. and YouNameItWeIntegrateIt.com over the
         past 3 months. The engineers who have left the Foobar
         corporation and its partners were rumored to be working on
         the next generation of server products and applications which
         will directly compete with Foobar's Foo 20.9 servers. Most of
         the engineers have relocated to Hawaii where the Gorilla
         Corporation's server development is located.
      </par>
   </content>
   <date>1-20-2000</date>
   <news_agent>Reliable News Corporation</news_agent>
</news_item>
</news>
                    

In addition, the following data, listing the partners and competitors of companies, is found in the file "company-data.xml".

1.6.4 Queries and Results

1.7 Use Case "NS" - Queries Using Namespaces

This use case performs a variety of queries on namespace-qualified names.

1.7.3 Sample Data

<?xml version="1.0" encoding="ISO-8859-1"?>

<ma:AuctionWatchList
    xmlns:ma="http://www.example.com/AuctionWatch"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:anyzone="http://www.example.com/auctioneers#anyzone"
    xmlns:eachbay="http://www.example.com/auctioneers#eachbay"
    xmlns:yabadoo="http://www.example.com/auctioneers#yabadoo"
>

<!-- ________________________________________________________________________________ -->

<ma:Auction anyzone:ID="0321K372910">

    <ma:AuctionHomepage
        xlink:type="simple"
        xlink:href="http://www.example.com/item/0321K372910"
    />

    <ma:Schedule>
        <ma:Open    xmlns:dt="http://www.w3.org/2001/XMLSchema"
                dt:type="timeInstant">2000-03-21:07:41:34-05:00</ma:Open>
        <ma:Close    xmlns:dt="http://www.w3.org/2001/XMLSchema"
                dt:type="timeInstant">2000-03-23:07:41:34-05:00</ma:Close>
    </ma:Schedule>
    
    <ma:Price>
        <ma:Start ma:currency="USD">3.00</ma:Start>
        <ma:Current ma:currency="USD">10.00</ma:Current>
        <ma:Number_of_Bids>5</ma:Number_of_Bids>
    </ma:Price>

    <ma:Trading_Partners>
        <ma:High_Bidder>
            <eachbay:ID>RecordsRUs</eachbay:ID>
            <eachbay:PositiveComments>231</eachbay:PositiveComments>
            <eachbay:NeutralComments>2</eachbay:NeutralComments>
            <eachbay:NegativeComments>5</eachbay:NegativeComments>
            <ma:MemberInfoPage
                xlink:type="simple"
                xlink:href="http://auction.eachbay.com/members?get=RecordsRUs"
                xlink:role="ma:MemberInfoPage"
            />            
        </ma:High_Bidder>
        <ma:Seller>
            <anyzone:ID>VintageRecordFreak</anyzone:ID>
            <anyzone:Member_Since>October 1999</anyzone:Member_Since>
            <anyzone:Rating>5</anyzone:Rating>
            <ma:MemberInfoPage
               xlink:type="simple"
               xlink:href="http://auction.anyzone.com/members/VintageRecordFreak"
               xlink:role="ma:MemberInfoPage"
            />
        </ma:Seller>
    </ma:Trading_Partners>

    <ma:Details>
        <record xmlns="http://www.example.org/music/records">
            <artist>Miles Davis</artist>
            <title>In a Silent Way</title>
            <recorded>1969</recorded>
            <label>Columbia Records</label>

            <remark>With Miles Davis (trumpet), Herbie Hancock (Electric
                Piano), Chick Corea (Electric Piano), Wayne Shorter
                (Tenor Sax), Josef Zawinul (Electric Piano &amp;
                Organ), John McLaughlin (Guitar), and Tony Williams
                (Drums).  The liner notes were written by Frank Glenn,
                and the record is in fine condition.</remark>

        </record>
    </ma:Details>

</ma:Auction>

<!-- ________________________________________________________________________________ -->


<ma:Auction yabadoo:ID="13143816">

    <ma:AuctionHomepage
        xlink:type="simple"
        xlink:href="http://auctions.yabadoo.com/auction/13143816"
    />

    <ma:Schedule>
        <ma:Open    xmlns:dt="http://www.w3.org/2001/XMLSchema"
                dt:type="timeInstant">2000-03-19:17:03:00-04:00</ma:Open>
        <ma:Close    xmlns:dt="http://www.w3.org/2001/XMLSchema"
                dt:type="timeInstant">2000-03-29:17:03:00-04:00</ma:Close>
    </ma:Schedule>
    
    <ma:Price>
        <ma:Start ma:currency="USD">3.00</ma:Start>
        <ma:Current ma:currency="USD">3.00</ma:Current>
        <ma:Number_of_Bids>0</ma:Number_of_Bids>
    </ma:Price>

    <ma:Trading_Partners>
        <ma:High_Bidder>
            <eachbay:ID>VintageRecordFreak</eachbay:ID>
            <eachbay:PositiveComments>232</eachbay:PositiveComments>
            <eachbay:NeutralComments>0</eachbay:NeutralComments>
            <eachbay:NegativeComments>0</eachbay:NegativeComments>
            <ma:MemberInfoPage
                xlink:type="simple"
                xlink:href="http://auction.eachbay.com/showRating/user=VintageRecordFreak"
                xlink:role="ma:MemberInfoPage"
            />            
        </ma:High_Bidder>
        <ma:Seller xmlns:seller="http://www.example.com/auctioneers#eachbay">
            <seller:ID>StarsOn45</seller:ID>
            <seller:PositiveComments>80</seller:PositiveComments>
            <seller:NeutralComments>1</seller:NeutralComments>
            <seller:NegativeComments>2</seller:NegativeComments>
            <ma:MemberInfoPage
                xlink:type="simple"
                xlink:href="http://auction.eachbay.com/showRating/user=StarsOn45"
                xlink:role="ma:MemberInfoPage"
            />            
        </ma:Seller>
    </ma:Trading_Partners>

    <ma:Details>
        <record xmlns="http://www.example.org/music/records">
            <artist>Wynton Marsalis</artist>
            <title>Think of One ...</title>
            <recorded>1983</recorded>
            <label>Columbia Records</label>
            <remark xml:lang="en">Columbia Records 12" 33-1/3 rpm LP,
                #FC-38641, Stereo. The record is still clean and shiny
                and looks unplayed (looks like NM condition).  The
                cover has very light surface and edge wear.</remark>
            <remark xml:lang="de">Columbia Records 12" 33-1/3 rpm LP,
                #FC-38641, Stereo. Die Platte ist noch immer sauber
                und glänzend und sieht ungespielt aus
                (NM Zustand). Das Cover hat leichte Abnutzungen an
                Oberfläche und Ecken.</remark>
        </record>
    </ma:Details>

</ma:Auction>         

</ma:AuctionWatchList>

1.7.4 Queries and Results

1.7.4.3 Q3

Select all elements that have an attribute whose name is in the XML Schema namespace.

Solution in XQuery:

Expected Result:

<Q3>
	<ma:Open 
	  dt:type="timeInstant" 
	  xmlns:anyzone="http://www.example.com/auctioneers#anyzone" 
	  xmlns:dt="http://www.w3.org/2001/XMLSchema" 
	  xmlns:eachbay="http://www.example.com/auctioneers#eachbay" 
	  xmlns:ma="http://www.example.com/AuctionWatch"
	  xmlns:xlink="http://www.w3.org/1999/xlink" 
	  xmlns:yabadoo="http://www.example.com/auctioneers#yabadoo">2000-03-21:07:41:34-05:00</ma:Open>
	<ma:Close 
	  dt:type="timeInstant" 
	  xmlns:anyzone="http://www.example.com/auctioneers#anyzone" 
	  xmlns:dt="http://www.w3.org/2001/XMLSchema" 
	  xmlns:eachbay="http://www.example.com/auctioneers#eachbay" 
	  xmlns:ma="http://www.example.com/AuctionWatch"
	  xmlns:xlink="http://www.w3.org/1999/xlink" 
	  xmlns:yabadoo="http://www.example.com/auctioneers#yabadoo">2000-03-23:07:41:34-05:00</ma:Close>
	<ma:Open 
	  dt:type="timeInstant" 
	  xmlns:anyzone="http://www.example.com/auctioneers#anyzone" 
	  xmlns:dt="http://www.w3.org/2001/XMLSchema" 
	  xmlns:eachbay="http://www.example.com/auctioneers#eachbay" 
	  xmlns:ma="http://www.example.com/AuctionWatch"
	  xmlns:xlink="http://www.w3.org/1999/xlink" 
	  xmlns:yabadoo="http://www.example.com/auctioneers#yabadoo">2000-03-19:17:03:00-04:00</ma:Open>
	<ma:Close 
	  dt:type="timeInstant" 
	  xmlns:anyzone="http://www.example.com/auctioneers#anyzone" 
	  xmlns:dt="http://www.w3.org/2001/XMLSchema" 
	  xmlns:eachbay="http://www.example.com/auctioneers#eachbay" 
	  xmlns:ma="http://www.example.com/AuctionWatch"
	  xmlns:xlink="http://www.w3.org/1999/xlink" 
	  xmlns:yabadoo="http://www.example.com/auctioneers#yabadoo">2000-03-29:17:03:00-04:00</ma:Close>
</Q3>

1.8 Use Case "PARTS" - Recursive Parts Explosion

This use case illustrates how a recursive query might be used to construct a hierarchic document of arbitrary depth from flat structures stored in a database.

1.9 Use Case "STRONG" - queries that exploit strongly typed data

1.9.2 Schema

The schema for this example is the International Purchase Order schema taken from the XML Schema Primer, which imports a schema for addresses. The main schema is found in a schema document named "ipo.xsd":


<?xml version="1.0"?>
<schema targetNamespace="http://www.example.com/IPO"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:ipo="http://www.example.com/IPO">

  <annotation>
    <documentation xml:lang="en">
      International Purchase order schema for Example.com
      Copyright 2000 Example.com. All rights reserved.
    </documentation>
  </annotation>

  <!-- include address constructs -->
  <include
    schemaLocation="address.xsd"/>

  <element name="purchaseOrder" type="ipo:PurchaseOrderType"/>

  <element name="comment" type="string"/>
  <element name="shipComment" type="string" substitutionGroup="ipo:comment"/>
  <element name="customerComment" type="string" substitutionGroup="ipo:comment"/>

  <complexType name="PurchaseOrderType">
    <sequence>
      <element name="shipTo"     type="ipo:Address"/>
      <element name="billTo"     type="ipo:Address"/>
      <element ref="ipo:comment" minOccurs="0"/>
      <element name="items"      type="ipo:Items"/>
    </sequence>
    <attribute name="orderDate" type="date"/>
  </complexType>

  <complexType name="Items">
    <sequence>
      <element name="item" minOccurs="0" maxOccurs="unbounded">
        <complexType>
          <sequence>
            <element name="productName" type="string"/>
            <element name="quantity">
              <simpleType>
                <restriction base="positiveInteger">
                  <maxExclusive value="100"/>
                </restriction>
              </simpleType>
            </element>
            <element name="USPrice"    type="decimal"/>
            <element ref="ipo:comment" minOccurs="0" maxOccurs="unbounded"/>
            <element name="shipDate"   type="date" minOccurs="0" maxOccurs="unbounded"/>
          </sequence>
          <attribute name="partNum" type="ipo:SKU" use="required"/>
        </complexType>
      </element>
    </sequence>
  </complexType>

  <simpleType name="SKU">
    <restriction base="string">
      <pattern value="\d{3}-[A-Z]{2}"/>
    </restriction>
  </simpleType>

</schema>
					    

The address constructs are found in a schema document named "address.xsd":

1.9.4 Queries

1.9.4.2 Q2

Write a function that tests an American address to check if it has the right zip code.

In our solution, we will assume zip code data is stored in a file named "zips.xml", which looks like this.

The corresponding schema document is named "zips.xsd":

Solution in XQuery:

An attempt to call this function with an element of the wrong address type raises an error. For instance, you can not call z:zip-ok() with an element of type UKAddress.

Note that the parameter for this function specifies the type rather than the element name, since it is written to be used with any element that has the proper address type - for instance, in our sample schema, 'billTo' and 'shipTo' are two different elements which may both have the USAddress type.

1.9.4.3 Q3

Write a function that tests a UK address to see if it has the right postal code.

For England, we store the information needed to test postal codes in a file named "postals.xml", which looks like this:

Here is the schema for the above file.

Solution in XQuery:

1.9.4.7 Q7

Write a function that returns the text of a comment. Call this function for each shipping comment found in an item shipped to Helen Zoe on the date 1999-12-01.

Our source schema models comments with the following substitution groups:

The following sample data contains instances of these substitution groups:

Solution in XQuery:

In this query, the function specifies ipo:comment as the name of the element, but any element in the substitution group of ipo:comment may also be passed to this function. That means that we can call the same function for ipo:shipComment elements or ipo:customerComment elements - for instance, the following query also succeeds:

1.9.4.10 Q10

Write a function that determines whether the person listed in a billTo element is known to be a deadbeat, using a US database.

This query assumes that "deadbeats.xml" lists the names deadbeats in the following format:

Solution in XQuery:

Expected Output:

Note that this function specifies both the element name and the type. The element name is specified because we do not want to embarrass recipients of gifts by calling this function for the shipping address by mistake. The type is specified because we would need to use a different database to identify deadbeats in other countries.

Also note that the XML file in this example has no schema. We assume that the processor omits validation or does lax validation.

1.9.4.12 Q12

In [XMLSchema0], a Quarterly Report is created, summarizing the types of products that have been billed on a per region basis. It creates the following sample report:

<purchaseReport
  xmlns="http://www.example.com/Report"
  period="P3M" periodEnding="1999-12-31">

 <regions>
  <zip code="95819">
   <part number="872-AA" quantity="1"/>
   <part number="926-AA" quantity="1"/>
   <part number="833-AA" quantity="1"/>
   <part number="455-BX" quantity="1"/>
  </zip>
  <zip code="63143">
   <part number="455-BX" quantity="4"/>
  </zip>
 </regions>

 <parts>
  <part number="872-AA">Lawnmower</part>
  <part number="926-AA">Baby Monitor</part>
  <part number="833-AA">Lapis Necklace</part>
  <part number="455-BX">Sturdy Shelves</part>
 </parts>

</purchaseReport> 

This is the schema given for the above report:

<schema targetNamespace="http://www.example.com/Report"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:r="http://www.example.com/Report"
        xmlns:xipo="http://www.example.com/IPO"
        elementFormDefault="qualified">

 <!-- for SKU -->
 <import namespace="http://www.example.com/IPO"/>

 <annotation>
  <documentation xml:lang="en">
   Report schema for Example.com
   Copyright 2000 Example.com. All rights reserved.
  </documentation> 
 </annotation>

 <element name="purchaseReport">
  <complexType>
   <sequence>
    <element name="regions" type="r:RegionsType">
     <keyref name="dummy2" refer="r:pNumKey">
      <selector xpath="r:zip/r:part"/>
      <field xpath="@number"/>
     </keyref>
    </element>

    <element name="parts" type="r:PartsType"/>
   </sequence>
   <attribute name="period"       type="duration"/>
   <attribute name="periodEnding" type="date"/>
  </complexType>
  
  <unique name="dummy1">
   <selector xpath="r:regions/r:zip"/>
   <field xpath="@code"/>
  </unique>

  <key name="pNumKey">
   <selector xpath="r:parts/r:part"/>
   <field xpath="@number"/>
  </key>
 </element>

 <complexType name="RegionsType">
  <sequence>
   <element name="zip" maxOccurs="unbounded">
    <complexType>
     <sequence>
      <element name="part" maxOccurs="unbounded">
       <complexType>
        <complexContent>
         <restriction base="anyType">
          <attribute name="number"   type="xipo:SKU"/>
          <attribute name="quantity" type="positiveInteger"/>
         </restriction>
        </complexContent>
       </complexType>
      </element>
     </sequence>
     <attribute name="code" type="positiveInteger"/>
    </complexType>
   </element>
  </sequence>
 </complexType>

 <complexType name="PartsType">
  <sequence>
   <element name="part" maxOccurs="unbounded">
    <complexType>
     <simpleContent>
      <extension base="string">
       <attribute name="number" type="xipo:SKU"/>
      </extension>
     </simpleContent>
    </complexType>
   </element>
  </sequence>
 </complexType>

</schema> 

This report, which lists products sold by zip code, is based on the same international purchase report used in previous queries.

Here is a query that generates the desired report from a collection that contains US purchase orders:

declare namespace rpt="http://www.example.com/Report";

let $orders := doc('ipo.xml')/schema-element(ipo:purchaseOrder)
                  [@orderDate ge xs:date("1999-09-01")
                   and @orderDate le xs:date("1999-12-31")]
let $items := $orders/items/item
let $zips := distinct-values($orders/billTo/zip)
let $parts := distinct-values($items/@partNum)
return
 <rpt:purchaseReport>
  <rpt:regions>
    {
     for $zip in $zips
     order by $zip
     return
      <rpt:zip code="{$zip}">
       {
        for $part in $parts
        let $hits := $orders[ billTo/zip = $zip and items/item/@partNum = $part]
        let $quantity := sum($hits//item[@partNum=$part]/quantity)
        where count($hits) > 0
        order by $part
        return
         <rpt:part number="{$part}" quantity="{$quantity}"/>
       }
      </rpt:zip>
    }
  </rpt:regions>
  <rpt:parts>
   {
     for $part in $parts
     return
      <rpt:part number="{$part}">
       {
         string($items[@partNum = $part]/productName)
       }
      </rpt:part>   
   }
  </rpt:parts>
</rpt:purchaseReport>
            

A Acknowledgements

The editors thank the members of the XML Query Working Group, which produced the material in this document.

The use cases in this paper were contributed by the following individuals:

Use Case "R"Don Chamberlin
Use Case "XMP"Mary Fernandez, Jerome Simeon, Phil Wadler
Use Case "TREE"Jonathan Robie
Use Case "PARTS" Michael Rys
Use Case "NS"Ingo Macherius
Use Case "STRING"Umit Yalcinalp
Use Case "SEQ"Jonathan Robie
Use Case "SGML"Paula Angerstein
Use Case "STRONG"Jonathan Robie and Phil Wadler. Schemas and data taken from .

Use case "XMP" has been previously published in [Fernandez]. Use cases "Tree" and "Seq" have been previously published in [Robie99].

The editors also wish to thank the members of the other W3C Working Groups who have commented on earlier drafts, and Michael Dyck and for his critical reading and helpful suggestions. Michael Wenger found several bugs, and also found more elegant solutions to some of the use cases, which are now included in this document.

B Change Log (Non-Normative)

B.3 11 July 2005

Aligned with current XQuery Working Draft.

Fixed the following bugs.

  1. rdb-queries-results-q9 now uses month-from-date() and year-from-date(). The "get-" prefix, now obsolete, has been removed. Fixes Bug 119.

  2. Removed whitespace from the price element in the source document for Use Case "XMP" - it was <price> 65.95</price>, and is now <price> 65.95</price>. Fixes Bug 121.

  3. Removed trailing whitespace from the <remark/> elements used in "auction.xml". Fixes bug Bug 124.

  4. Need to discuss Bug 148. Did not see the problems with Q1 and Q2 in the document. Have some questions about the best treatment of Q4 and Q5.

  5. Fixed many errors in Use Case "Strong" as proposed here.

C References (Non-Normative)

The following references are some of the works considered by the WG in deriving its use cases.

Cotton98
Candidate Requirements for XML Query, Paul Cotton and Ashok Malhotra, 1998. In Query Languages 98 (QL'98).
DOM
Document Object Model (DOM), Level 2 Specification. W3C Candidate Recommendation.
FandO
XQuery 1.0 and XPath 2.0 Functions and Operators, Ashok Malhotra, Jim Melton, and Norman Walsh, Editors. World Wide Web Consortium, 3 Nov 2005. This version is http://www.w3.org/TR/2005/CR-xpath-functions-20051103/. The latest version is available at http://www.w3.org/TR/xpath-functions/.
Fernandez
XML Query Languages: Experiences and Exemplars, Mary Fernandez, Jerome Simeon, Philip Wadler, 1999.
Infoset
XML Information Set (Second Edition), John Cowan and Richard Tobin, Editors. World Wide Web Consortium, 04 Feb 2004. This version is http://www.w3.org/TR/2004/REC-xml-infoset-20040204. The latest version is available at http://www.w3.org/TR/xml-infoset.
Maier98
Database Desiderata for an XML Query Language, David Maier, 1998. In Query Languages 98 (QL'98).
Namespaces
Namespaces in XML, Tim Bray, Dave Hollander, and Andrew Layman, Editors. World Wide Web Consortium, 14 Jan 1999. This version is http://www.w3.org/TR/1999/REC-xml-names-19990114. The latest version is available at http://www.w3.org/TR/REC-xml-names.
Robie99
The Tree Structure of XML Queries, Jonathan Robie.
XML
Extensible Markup Language (XML) 1.0 (Third Edition), C. M. Sperberg-McQueen, Eve Maler, Tim Bray, et. al., Editors. World Wide Web Consortium, 04 Feb 2004. This version is http://www.w3.org/TR/2004/REC-xml-20040204. The latest version is available at http://www.w3.org/TR/REC-xml.
XMLSchema0
XML Schema Part 0: Primer Second Edition, David C. Fallside and Priscilla Walmsley, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-0/.
XMLSchema1
XML Schema Part 1: Structures Second Edition, David Beech, Noah Mendelsohn, Murray Maloney, and Henry S. Thompson, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-1/.
XMLSchema2
XML Schema Part 2: Datatypes Second Edition, Paul V. Biron and Ashok Malhotra, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-2/.
XPath
XML Path Language (XPath) 2.0, Don Chamberlin , Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 3 Nov 2005. This version is http://www.w3.org/TR/2005/CR-xpath20-20051103/. The latest version is available at http://www.w3.org/TR/xpath20/.
XQuery
XQuery 1.0: An XML Query Language, Don Chamberlin , Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 3 Nov 2005. This version is http://www.w3.org/TR/2005/CR-xquery-20051103/. The latest version is available at http://www.w3.org/TR/xquery/.
XQuery Requirements
XML Query (XQuery) Requirements, Don Chamberlin, Peter Fankhauser, Massimo Marchiori, and Jonathan Robie, Editors. World Wide Web Consortium, 3 Jun 2005. This version is http://www.w3.org/TR/2005/WD-xquery-requirements-20050603/. The latest version is available at http://www.w3.org/TR/xquery-requirements/.
XSLT
XSL Transformations (XSLT) Version 1.0, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The latest version is available at http://www.w3.org/TR/xslt.
Use Case Sample Queries
Queries from this document, presented in a single file
XQuery Sample Queries
Queries from the XQuery document, presented in a single file.