Adding XML Elements and Attributes
Sometimes you want to reorganize or transform the elements in the input documents into differently named or structured elements. XML constructors can be used to create elements and attributes that appear in the query results.
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.
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>
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 ...
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