Skip to Content
XQuery, 2nd Edition
book

XQuery, 2nd Edition

by Priscilla Walmsley
December 2015
Intermediate to advanced
762 pages
19h 13m
English
O'Reilly Media, Inc.
Content preview from XQuery, 2nd Edition

Chapter 5. Adding Elements and Attributes to Results

Most queries include some XML elements and attributes that structure the results. In the previous chapter, we saw how to use path expressions to copy elements and attributes from input documents. After a brief review of this technique, this chapter explains how you can create entirely new elements and attributes and include them in your results.

There are two ways to create new elements and attributes: direct constructors and computed constructors. Direct constructors, which use an XML-like syntax, are useful for creating elements and attributes whose names are fixed. Computed constructors, on the other hand, allow for names that are generated dynamically in the query.

Including Elements and Attributes from the Input Document

Some queries simply include elements and attributes from the input document in the results. Example 5-1 includes certain selected name elements in the results.

Example 5-1. Including elements from the input document

Query

for $prod in doc("catalog.xml")/catalog/product[@dept = 'ACC']
return $prod/name

Results

<name language="en">Floppy Sun Hat</name>
<name language="en">Deluxe Travel Bag</name>

Note that because the entire name element is returned, the results include the name elements, not just their atomic values. In fact, if the query returns elements that have attributes and descendants, they are all part of the results. This is exhibited in Example 5-2.

Example 5-2. Including complex elements from the input document ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

XQuery

XQuery

Priscilla Walmsley
XSLT

XSLT

Doug Tidwell
Learning XSLT

Learning XSLT

Michael Fitzgerald

Publisher Resources

ISBN: 9781491915080Purchase bookErrata Page