Tải bản đầy đủ (.pdf) (511 trang)

XQuery potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.66 MB, 511 trang )

XQuery
Other XML resources from O’Reilly
Related titles
XSLT
Learning XSLT
XSLT Cookbook

XML in a Nutshell
Learning XML
Developing Feeds with RSS
and Atom
Java

and XML
XSLT 1.0 Pocket Reference
XML Hacks

XML Books Resource
Center
xml.oreilly.com is a complete catalog of O’Reilly’s books on
XML and related technologies, including sample chapters and
code examples.
XML.com helps you discover XML and learn how this Internet
technology can solve real-world problems in information man-
agement and electronic commerce.
Conferences
O’Reilly brings diverse innovators together to nurture the ideas
that spark revolutionary industries. We specialize in document-
ing the latest tools and systems, translating the innovator’s
knowledge into useful skills for those in the trenches. Visit con-


ferences.oreilly.com for our upcoming events.
Safari Bookshelf (safari.oreilly.com) is the premier online refer-
ence library for programmers and IT professionals. Conduct
searches across more than 1,000 books. Subscribers can zero in
on answers to time-critical questions in a matter of seconds.
Read the books on your Bookshelf from cover to cover or sim-
ply flip to the page you need. Try it today for free.
XQuery
Priscilla Walmsley
Beijing

Cambridge

Farnham

Köln

Paris

Sebastopol

Taipei

Tokyo
XQuery
by Priscilla Walmsley
Copyright © 2007 Priscilla Walmsley. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions

are also available for most titles (safari.oreilly.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or
Editor:
Simon St.Laurent
Production Editor:
Lydia Onofrei
Proofreader:
Lydia Onofrei
Indexer:
Ellen Troutman-Zaig
Cover Designer:
Karen Montgomery
Interior Designer:
David Futato
Illustrators:
Robert Romano and Jessamyn Read
Printing History:
April 2007: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. XQuery, the image of a satyr tragopan, and related trade dress are trademarks of
O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information
contained herein.
This book uses RepKover

, a durable and flexible lay-flat binding.

ISBN-10: 0-596-00634-9
ISBN-13: 978-0-596-00634-1
[M]
v
Table of Contents
Preface
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xi
1. Introduction to XQuery
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
What Is XQuery? 1
Easing into XQuery 3
Path Expressions 5
FLWORs 6
Adding XML Elements and Attributes 7
Functions 10
Joins 10
Aggregating and Grouping Values 11
2. XQuery Foundations
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12
The Design of the XQuery Language 12
XQuery in Context 13
Processing Queries 15
The XQuery Data Model 17
Types 24
Namespaces 24
3. Expressions: XQuery Building Blocks
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26
Categories of Expressions 26
Keywords and Names 27
Whitespace in Queries 27
Literals 28
Variables 28
Function Calls 29
vi | Table of Contents
Comments 29
Evaluation Order and Parentheses 30
Comparison Expressions 30
Conditional (if-then-else) Expressions 35
Logical (and/or) Expressions 37
4. Navigating Input Documents Using Paths
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
39
Path Expressions 39
Predicates 46
Dynamic Paths 52
Input Documents 52
A Closer Look at Context 55
5. Adding Elements and Attributes to Results
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
57
Including Elements and Attributes from the Input Document 57
Direct Element Constructors 58
Computed Constructors 68
6. Selecting and Joining Using FLWORs
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
72

Selecting with Path Expressions 72
FLWOR Expressions 72
Quantified Expressions 79
Selecting Distinct Values 81
Joins 81
7. Sorting and Grouping
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
85
Sorting in XQuery 85
Grouping 93
Aggregating Values 94
8. Functions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
99
Built-in Versus User-Defined Functions 99
Calling Functions 99
User-Defined Functions 103
9. Advanced Queries
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
110
Copying Input Elements with Modifications 110
Working with Positions and Sequence Numbers 115
Combining Results 118
Using Intermediate XML Documents 119
Table of Contents | vii
10. Namespaces and XQuery
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
123
XML Namespaces 123
Namespaces and XQuery 127

Namespace Declarations in Queries 128
Controlling Namespace Declarations in Your Results 135
11. A Closer Look at Types
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
141
The XQuery Type System 141
The Built-in Types 143
Types, Nodes, and Atomic Values 145
Type Checking in XQuery 146
Automatic Type Conversions 147
Sequence Types 151
Constructors and Casting 155
12. Queries, Prologs, and Modules
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
160
Structure of a Query: Prolog and Body 160
Assembling Queries from Multiple Modules 163
Variable Declarations 166
Declaring External Functions 168
13. Using Schemas with XQuery
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
170
What Is a Schema? 170
Why Use Schemas with Queries? 171
W3C XML Schema: A Brief Overview 172
In-Scope Schema Definitions 175
Schema Validation and Type Assignment 178
Sequence Types and Schemas 183
14. Static Typing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

185
What Is Static Typing? 185
The Typeswitch Expression 187
The Treat Expression 189
Type Declarations 190
The zero-or-one, one-or-more, and exactly-one Functions 192
15. Principles of Query Design
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
193
Query Design Goals 193
Clarity 193
Modularity 196
viii | Table of Contents
Robustness 196
Error Handling 199
Performance 201
16. Working with Numbers
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
204
The Numeric Types 204
Constructing Numeric Values 205
Comparing Numeric Values 206
Arithmetic Operations 207
Functions on Numbers 211
17. Working with Strings
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
213
The xs:string Type 213
Constructing Strings 213
Comparing Strings 214

Substrings 216
Finding the Length of a String 217
Concatenating and Splitting Strings 218
Manipulating Strings 220
Whitespace and Strings 222
Internationalization Considerations 223
18. Regular Expressions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
226
The Structure of a Regular Expression 226
Representing Individual Characters 228
Representing Any Character 229
Representing Groups of Characters 230
Character Class Expressions 233
Reluctant Quantifiers 235
Anchors 236
Back-References 237
Using Flags 238
Using Sub-Expressions with Replacement Variables 239
19. Working with Dates, Times, and Durations
. . . . . . . . . . . . . . . . . . . . . . . . . . .
242
The Date and Time Types 242
The Duration Types 246
Extracting Components of Dates, Times, and Durations 248
Using Arithmetic Operators on Dates, Times, and Durations 249
The Date Component Types 252
Table of Contents | ix
20. Working with Qualified Names, URIs, and IDs
. . . . . . . . . . . . . . . . . . . . . . . .

254
Working with Qualified Names 254
Working with URIs 259
Working with IDs 264
21. Working with Other XML Components
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
267
XML Comments 267
Processing Instructions 269
Documents 272
Text Nodes 274
XML Entity and Character References 278
CDATA Sections 280
22. Additional XQuery-Related Standards
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
282
Serialization 282
XQueryX 284
XQuery Update Facility 285
Full-Text Search 285
XQuery API for Java (XQJ) 287
23. Implementation-Specific Features
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
289
Conformance 289
XML Version Support 290
Setting the Query Context 290
Option Declarations and Extension Expressions 291
Specifying Serialization Parameters 293
24. XQuery for SQL Users

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
294
Relational Versus XML Data Models 294
Comparing SQL Syntax with XQuery Syntax 296
Combining SQL and XQuery 303
SQL/XML 306
25. XQuery for XSLT Users
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
307
XQuery and XPath 307
XQuery Versus XSLT 307
Differences Between XQuery 1.0/XPath 2.0 and XPath 1.0 314
x | Table of Contents
A. Built-in Function Reference
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
319
B. Built-in Types
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
411
C. Error Summary
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
440
Index
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
465
xi
Preface1
This book provides complete coverage of the W3C XQuery 1.0 standard that was
finalized in January 2007. In addition, it provides the background knowledge in
namespaces, schemas, built-in types, and regular expressions that is relevant to writ-

ing XML queries.
This book is designed for query writers who have some knowledge of XML basics
but not necessarily advanced knowledge of XML-related technologies. It can be used
as a tutorial, by reading it cover to cover, and as a reference, by using the compre-
hensive index and appendixes.
Contents of This Book
The book is organized into six parts:
1. Chapters 1 and 2 provide a high-level overview and quick tour of XQuery.
2. Chapters 3–9 provide enough information to write sophisticated queries, with-
out being bogged down by the details of types, namespaces, and schemas.
3. Chapters 10–15 introduce some advanced concepts for users who want to take
advantage of modularity, namespaces, typing, and schemas.
4. Chapters 16–23 provide guidelines for working with specific types of data, such
as numbers, strings, dates, URIs, and processing instructions.
5. Chapters 24 and 25 describe XQuery’s relationship to SQL and XSLT.
6. Appendixes A, B, and C provide a complete alphabetical reference to the built-in
functions, types, and error messages.
Reading the Syntax Diagrams
This book includes syntax diagrams as an option for readers who want a more visual
representation of XQuery expression syntax. Each syntax diagram is accompanied by
xii
|
Preface
explanatory text and examples. Figure P-1 illustrates the components of a syntax dia-
gram, showing the schema import syntax as an example.
Rules for interpreting the syntax diagrams are:
• Parts of the diagram in
constant width font are literal values. In Figure P-1,
import schema and at should appear literally in your query.
• Quotes that appear in syntax diagrams also must appear in your query.

Figure P-1 shows that the
<namespace-name> must be surrounded by quotes,
whereas the
<prefix> must not. Either single or double quotes can be used in
XQuery, but only double quotes are included in the diagrams for simplicity.
• Where you can specify a value, such as a name, a descriptive name for that value
appears in constant width italic and is surrounded by angle brackets. Figure P-1
shows that you fill in the
<namespace-name>, <prefix>, and <location> with your
own values.
• Multiple options are indicated by parallel lines in the diagram. Figure P-1 shows
that you may choose to specify a namespace prefix or
default element namespace.
• Optional parts of the expression are indicated by an arrow that bypasses the
main arrow. In Figure P-1, it is not necessary to include the
namespace <prefix>=
or the default element namespace keywords.
• Repeating parts of an expression are indicated by an arrow that returns to the
beginning. Figure P-1 shows that you can specify multiple
<location>s (pre-
ceded by commas) as part of the
at clause.
Conventions Used in This Book
Constant width is used for:
• Code examples and fragments
• Anything that might appear in an XML document, including element names,
tags, attribute values, and processing instructions
• Anything that might appear in a program, including keywords, operators,
method names, class names, and literals
Figure P-1. Example syntax diagram

import schema
namespace <prefix> =
default element namespace
"<namespace-name>"
at "<location>"
;
,
Preface
|
xiii
Constant width bold is used for:
• Emphasis in code examples and fragments
Italic is used for:
• New terms where they are defined
• Emphasis in body text
• Pathnames, filenames, and program names
• Host and domain names
This icon indicates a tip, suggestion, or general note.
This icon indicates a warning or caution.
This icon indicates a situation where compatibility issues may cause
surprises.
Significant code fragments, complete programs, and documents are generally placed
into a separate paragraph like this:
for $prod as element(*,ProductType) in doc("catalog.xml")/catalog/*
order by $prod/name
return $prod/name
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,

writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example
code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “XQuery by Priscilla Walmsley.
Copyright 2007 Priscilla Walmsley, 978-0-596-00634-1.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at
xiv
|
Preface
Useful Functions
This book contains a series of illustrative examples that are labeled Useful Function.
What sets them apart from regular examples is that they are likely to be directly use-
ful in your own queries. They range from string functions like
substring-after-last
and replace-first to functions that modify elements and attributes, such as add-
attribute
.
The useful functions included in this book are part of a large library of XQuery
functions called the FunctX XQuery Library, which is available at http://www.
xqueryfunctions.com. This library contains a wide variety of reusable XQuery func-
tions that can be searched or browsed by category. It also includes detailed descrip-
tions and example function calls.
We’d Like to Hear from You
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North

Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any addi-
tional information. You can access this page at:
/>To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our web site at:
.
Acknowledgments
I am deeply indebted to Michael Kay, not only for his detailed review of this book,
but also for his excellent Saxon XQuery implementation, without which I would not
have been able to reliably test the examples.
Preface
|
xv
Ron Bourret, Bob DuCharme, Tim Finney, Ashok Malhotra, Darin McBeath, Peter
Meggitt, Shannon Shiflett, and Bruno J. Walmsley (my father) provided extremely
helpful comments on, and assistance with, this book.
This project would not have been possible without Simon St.Laurent, who provided
editorial guidance and championed the book within O’Reilly. Thanks, Simon!
Finally, I would like to thank Doug, my partner, my love, for his constant support
and encouragement during the busy years I have spent writing this book.
1
Chapter 1
CHAPTER 1
Introduction to XQuery1

This chapter provides background on the purpose and capabilities of XQuery. It also
gives a quick introduction to the features of XQuery that are covered in more detail
later in the book. It is designed to provide a basic familiarity with the most com-
monly used kinds of expressions, without getting too bogged down in the details.
What Is XQuery?
The use of XML has exploded in recent years. An enormous amount of information
is now stored in XML, both in XML databases and in documents on a filesystem.
This includes highly structured data, such as sales figures, semistructured data such
as product catalogs and yellow pages, and relatively unstructured data such as let-
ters and books. Even more information is passed between systems as transitory XML
documents.
All of this data is used for a variety of purposes. For example, sales figures may be
useful for compiling financial statements that may be published on the Web, report-
ing results to the tax authorities, calculating bonuses for salespeople, or creating
internal reports for planning. For each of these uses, we are interested in different
elements of the data and expect it to be formatted and transformed according to our
needs.
XQuery is a query language designed by the W3C to address these needs. It allows
you to select the XML data elements of interest, reorganize and possibly transform
them, and return the results in a structure of your choosing.
Capabilities of XQuery
XQuery has a rich set of features that allow many different types of operations on
XML data and documents, including:
• Selecting information based on specific criteria
• Filtering out unwanted information
2
|
Chapter 1: Introduction to XQuery
• Searching for information within a document or set of documents
• Joining data from multiple documents or collections of documents

• Sorting, grouping, and aggregating data
• Transforming and restructuring XML data into another XML vocabulary or
structure
• Performing arithmetic calculations on numbers and dates
• Manipulating strings to reformat text
As you can see, XQuery can be used not just to extract sections of XML documents,
but also to manipulate and transform the results. One capability that XQuery 1.0
does not provide is updates, which would be particularly useful in the case of XML
data stored in databases. This is under development for a future version of XQuery.
Uses for XQuery
There are as many reasons to query XML as there are reasons to use XML. Some
examples of common uses for the XQuery language are:
• Extracting information from a relational database for use in a web service
• Generating reports on data stored in a database for presentation on the Web as
XHTML
• Searching textual documents in a native XML database and presenting the
results
• Pulling data from databases or packaged software and transforming it for appli-
cation integration
• Combining content from traditionally non-XML sources to implement content
management and delivery
• Ad hoc querying of standalone XML documents for the purposes of testing or
research
Processing Scenarios
XQuery’s sweet spot is querying bodies of XML content that are stored in databases.
For this reason, it is sometimes called the “SQL of XML.” Some of the earliest
XQuery implementations were in native XML database products. The term “native
XML database” generally refers to a database that is designed for XML content from
the ground up, as opposed to a traditionally relational database. Rather than being
oriented around tables and columns, its data model is based on hierarchical docu-

ments and collections of documents.
Native XML databases are most often used for narrative content and other data that is
less predictable than what you would typically store in a relational database. Examples
Easing into XQuery
|
3
of native XML database products that support XQuery are Berkeley DB XML, eXist
(which is open source), MarkLogic Server, TigerLogic XDMS, and X-Hive/DB.
These products provide the traditional capabilities of databases, such as data stor-
age, indexing, querying, loading, extracting, backup, and recovery. Most of them
also provide some added value in addition to their database capabilities. For exam-
ple, they might provide advanced full-text searching functionality, document conver-
sion services, or end-user interfaces.
Major relational database products, including Oracle 10g, IBM DB2 9, and Microsoft
SQL Server 2005, also have support for XML and XQuery. Early implementations of
XML in relational databases involved storing XML in table columns as blobs or char-
acter strings and providing query access to those columns. However, these vendors
are increasingly blurring the line between native XML databases and relational data-
bases with new features that allow you to store XML natively.
Other XQuery processors are not embedded in a database product, but work inde-
pendently. They might be used on physical XML documents stored as files on a file
system or on the Web. They might also operate on XML data that is passed in mem-
ory from some other process. The most notable product in this category is Saxon,
which has both open source and commercial versions.
Easing into XQuery
The rest of this chapter takes you through a set of example queries, each of which
builds on the previous one. Three XML documents are used repeatedly as input doc-
uments to the query examples throughout the book. They will be used so frequently
that it may be worth printing them from the companion web site so that you can
view them alongside the examples.

These three examples are quite simplistic, but they are useful for educational pur-
poses because they are easy to learn and remember while looking at query examples.
In reality, most XQuery queries will be executed against much more complex docu-
ments, and often against multiple documents as a group. However, in order to keep
the examples reasonably concise and clear, this book will work with smaller docu-
ments that have a representative mix of XML characteristics.
The
catalog.xml document is a product catalog containing general information
about products (Example 1-1).
Example 1-1. Product catalog input document (catalog.xml)
<catalog>
<product dept="WMN">
<number>557</number>
<name language="en">Fleece Pullover</name>
<colorChoices>navy black</colorChoices>
</product>
4
|
Chapter 1: Introduction to XQuery
The prices.xml document contains prices for the products, based on effective dates
(Example 1-2).
The
order.xml document is a simple order containing a list of products ordered (ref-
erenced by a number that matches the number used in
catalog.xml), along with
quantities and colors (Example 1-3).
<product dept="ACC">
<number>563</number>
<name language="en">Floppy Sun Hat</name>
</product>

<product dept="ACC">
<number>443</number>
<name language="en">Deluxe Travel Bag</name>
</product>
<product dept="MEN">
<number>784</number>
<name language="en">Cotton Dress Shirt</name>
<colorChoices>white gray</colorChoices>
<desc>Our <i>favorite</i> shirt!</desc>
</product>
</catalog>
Example 1-2. Price information input document (prices.xml)
<prices>
<priceList effDate="2006-11-15">
<prod num="557">
<price currency="USD">29.99</price>
<discount type="CLR">10.00</discount>
</prod>
<prod num="563">
<price currency="USD">69.99</price>
</prod>
<prod num="443">
<price currency="USD">39.99</price>
<discount type="CLR">3.99</discount>
</prod>
</priceList>
</prices>
Example 1-3. Order input document (order.xml)
<order num="00299432" date="2006-09-15" cust="0221A">
<item dept="WMN" num="557" quantity="1" color="navy"/>

<item dept="ACC" num="563" quantity="1"/>
<item dept="ACC" num="443" quantity="2"/>
<item dept="MEN" num="784" quantity="1" color="white"/>
<item dept="MEN" num="784" quantity="1" color="gray"/>
<item dept="WMN" num="557" quantity="1" color="black"/>
</order>
Example 1-1. Product catalog input document (catalog.xml) (continued)
Path Expressions
|
5
Path Expressions
The most straightforward kind of query simply selects elements or attributes from an
input document. This type of query is known as a path expression. For example, the
path expression:
doc("catalog.xml")/catalog/product
will select all the product elements from the catalog.xml document.
Path expressions are used to traverse an XML tree to select elements and attributes of
interest. They are similar to paths used for filenames in many operating systems.
They consist of a series of steps, separated by slashes, that traverse the elements and
attributes in the XML documents. In this example, there are three steps:
1.
doc("catalog.xml") calls an XQuery function named doc, passing it the name of
the file to open
2.
catalog selects the catalog element, the outermost element of the document
3.
product selects all the product children of catalog
The result of the query will be the four product elements, exactly as they appear
(with the same attributes and contents) in the input document. Example 1-4 shows
the complete result.

Path expressions can also return attributes, using the @ symbol. For example, the
path expression:
doc("catalog.xml")/*/product/@dept
Example 1-4. Four product elements selected from the catalog
<product dept="WMN">
<number>557</number>
<name language="en">Fleece Pullover</name>
<colorChoices>navy black</colorChoices>
</product>
<product dept="ACC">
<number>563</number>
<name language="en">Floppy Sun Hat</name>
</product>
<product dept="ACC">
<number>443</number>
<name language="en">Deluxe Travel Bag</name>
</product>
<product dept="MEN">
<number>784</number>
<name language="en">Cotton Dress Shirt</name>
<colorChoices>white gray</colorChoices>
<desc>Our <i>favorite</i> shirt!</desc>
</product>
6
|
Chapter 1: Introduction to XQuery
will return the four dept attributes in the input document. The asterisk (*) can be
used as a wildcard to indicate any element name. In this example, the path will
return any
product children of the outermost element, regardless of the outermost

element’s name. Alternatively, you can use a double slash (//) to return
product ele-
ments that appear anywhere in the catalog document, as in:
doc("catalog.xml")//product/@dept
In addition to traversing the XML document, a path expression can contain predi-
cates that filter out elements or attributes that do not meet a particular criterion.
Predicates are indicated by square brackets. For example, the path expression:
doc("catalog.xml")/catalog/product[@dept = "ACC"]
contains a predicate. It selects only those product elements whose dept attribute
value is
ACC.
When a predicate contains a number, it serves as an index. For example:
doc("catalog.xml")/catalog/product[2]
will return the second product element in the catalog.
Path expressions are convenient because of their compact, easy-to-remember syntax.
However, they have a limitation: they can only return elements and attributes as they
appear in input documents. Any elements selected in a path expression appear in the
results with the same names, the same attributes and contents, and in the same order
as in the input document. When you select the
product elements, you get them with
all of their children and with their
dept attributes. Path expressions are covered in
detail in Chapter 4.
FLWORs
The basic structure of many (but not all) queries is the FLWOR expression. FLWOR
(pronounced “flower”) stands for “for, let, where, order by, return”, the keywords
used in the expression.
FLWORs, unlike path expressions, allow you to manipulate, transform, and sort
your results. Example 1-5 shows a simple FLWOR that returns the names of all
products in the ACC department.

Example 1-5. Simple FLWOR
Query
for $prod in doc("catalog.xml")/catalog/product
where $prod/@dept = "ACC"
order by $prod/name
return $prod/name
Results
<name language="en">Deluxe Travel Bag</name>
<name language="en">Floppy Sun Hat</name>
Adding XML Elements and Attributes
|
7
As you can see, the FLWOR is made up of several parts:
for
This clause sets up an iteration through the product nodes, and the rest of the
FLWOR is evaluated once for each of the four products. Each time, a variable
named
$prod is bound to a different product element. Dollar signs are used to
indicate variable names in XQuery.
where
This clause selects only products in the ACC department. This has the same
effect as a predicate (
[@dept = "ACC"]) in a path expression.
order by
This clause sorts the results by product name, something that is not possible
with path expressions.
return
This clause indicates that the product element’s name children should be returned.
The
let clause (the L in FLWOR) is used to set the value of a variable. Unlike a for

clause, it does not set up an iteration. Example 1-6 shows a FLWOR that returns the
same result as Example 1-5. The second line is a
let clause that assigns the product
element’s name child to a variable called $name. The $name variable is then referenced
later in the FLWOR, in both the
order by clause and the return clause.
The
let clause serves as a programmatic convenience that avoids repeating the same
expression multiple times. Using some implementations, it can also improve perfor-
mance, because the expression is evaluated only once instead of each time it is
needed.
This chapter has provided only very basic examples of FLWORs. In fact, FLWORs
can become quite complex. Multiple
for clauses are permitted, which set up itera-
tions within iterations. In addition, complex expressions can be used in any of the
clauses. FLWORs are discussed in detail in Chapter 6. Even more advanced exam-
ples of FLWORs are provided in Chapter 9.
Adding XML Elements and Attributes
Sometimes you want to reorganize or transform the elements in the input docu-
ments into differently named or structured elements. XML constructors can be used
to create elements and attributes that appear in the query results.
Example 1-6. Adding a let clause
for $product in doc("catalog.xml")/catalog/product
let $name := $product/name
where $product/@dept = "ACC"
order by $name
return $name
8
|
Chapter 1: Introduction to XQuery

Adding Elements
Suppose you want to wrap the results of your query in a different XML vocabulary,
for example XHTML. You can do this using a familiar XML-like syntax. To wrap the
name elements in a ul element, for instance, you can use the query shown in
Example 1-7. The
ul element represents an unordered list in XHTML.
This example is the same as Example 1-5, with the addition of the first and last lines.
In the query, the
ul start tag and end tag, and everything in between, is known as an
element constructor. The curly braces around the content of the
ul element signify
that it is an expression (known as an enclosed expression) that is to be evaluated. In
this case, the enclosed expression returns two elements, which become children of
ul.
Any content in an element constructor that is not inside curly braces appears in the
results as is. For example:
<h1>There are {count(doc("catalog.xml")//product)} products.</h1>
will return the result:
<h1>There are 4 products.</h1>
The content outside the curly braces, namely the strings “There are ” and “ products.”
appear literally in the results, as textual content of the
ul element.
The element constructor does not need to be the outermost expression in the query.
You can include element constructors at various places in your query. For example,
if you want to wrap each resulting
name element in its own li element, you could use
the query shown in Example 1-8. An
li element represents a list item in XHTML.
Example 1-7. Wrapping results in a new element
Query

<ul>{
for $product in doc("catalog.xml")/catalog/product
where $product/@dept='ACC'
order by $product/name
return $product/name
}</ul>
Results
<ul>
<name language="en">Deluxe Travel Bag</name>
<name language="en">Floppy Sun Hat</name>
</ul>
Example 1-8. Element constructor in FLWOR return clause
Query
<ul>{
for $product in doc("catalog.xml")/catalog/product
where $product/@dept='ACC'
order by $product/name

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×