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.
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
Query for $prod in doc("catalog.xml")/catalog/product[@dept = 'ACC'] return $prod Results <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>
The product
elements are included as they appear in the input document, with all attributes and children. If they are in a namespace in the input document, they will be in that same namespace in the results. There is no opportunity to add or remove children or attributes, or change the namespace name, when using path expressions. Techniques for making such modifications are covered later in this chapter.
18.226.187.233