Direct Element Constructors
You can also insert your own XML elements and attributes into the query results using XML constructors. There are two kinds of XML constructors: direct constructors, which use familiar XML-like syntax, and computed constructors, that allow you to generate dynamically the XML names used in the results.
A direct element constructor is a constructor of the first kind; it specifies an XML element (optionally with attributes) using XML-like syntax, as shown in Example 5-3. The result of the query is an XHTML fragment that presents the selected data.
Example 5-3. Constructing elements using XML-like syntax
Query <html> <h1>Product Catalog</h1> <ul>{ for $prod in doc("catalog.xml")/catalog/product return <li>number: {data($prod/number)}, name: {data($prod/name)}</li> }</ul> </html> Results <html> <h1>Product Catalog</h1> <ul> <li>number: 557, name: Fleece Pullover</li> <li>number: 563, name: Floppy Sun Hat</li> <li>number: 443, name: Deluxe Travel Bag</li> <li>number: 784, name: Cotton Dress Shirt</li> </ul> </html>
The h1, ul, and li elements appear in the results as XML elements. The h1 element constructor simply contains literal characters Product Catalog, which appear in the results as the content of h1. The ul element constructor, on the other hand, contains another XQuery expression enclosed in curly braces. This is known as an enclosed expression, and its value becomes the content of the ul element in the results. In this case, the enclosed expression evaluates ...
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.
Read now
Unlock full access