XQuery Adding Elements and Attributes
XML example document
We will continue to use this "books.xml" document in the examples below (the same XML file used in the sections above).
View the "books.xml" file in your browser.
Add elements and attributes to the result
As seen in the previous section, we can reference elements and attributes from the input file in the result:
for $x in doc("books.xml")/bookstore/book/title
order by $x
return $x
The XQuery expression above references the title element and the lang attribute in the result, like this:
The above XQuery expression returns the title elements in the same way they are described in the input document.
Now we want to add our own elements and attributes to the result!
Add HTML elements and text
Now we want to add HTML elements to the result. We will put the result in an HTML list:
Bookstore
- {data($x/title)}. Category: {data($x/@category)}
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return
}
The above XQuery expression will generate the following result:
Bookstore
- Everyday Italian. Category: COOKING
- Harry Potter. Category: CHILDREN
- Learning XML. Category: WEB
- XQuery Kick Start. Category: WEB
Add attributes to HTML elements
Next, we will use the category attribute as the class attribute in the HTML list:
Bookstore
- {data($x/title)}
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return
}
The above XQuery expression generates the following result:
Bookstore
- Everyday Italian
- Harry Potter
- Learning XML
- XQuery Kick Start