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 ...
Get XQuery, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.