Skip to main content

XQuery Adding Elements and Attributes

In XQuery you can add elements, attributes, HTML elements and text in the results from the input documents.

Let's see with an example.

Adding Elements and Attributes to the Result

Consider the following example that contains information about a bookstore.

books.xml
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<year>2022</year>
<price>39.99</price>
</book>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>
</bookstore>

The following XQuery expression returns the title elements the exact same way as they are described in the input document.

books.xqy
for $x in doc("books.xml")/bookstore/book/title  
order by $x
return $x

Now, we want to add other elements and attributes to the result.

How Add HTML Elements and Text

For example, we will put the result in an HTML list and some text:

<html>  
<body>

<h1>Bookstore</h1>

<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li>{data($x/title)}. Category: {data($x/@category)}</li>
}
</ul>

</body>
</html>

The XQuery expression above will generate the following result:

<html>
<body>

<h1>Bookstore</h1>

<ul>
<li>Harry Potter. Category: children</li>
<li>XQuery Tips. Category: web</li>
<li>Learn XML. Category: web</li>
</ul>

</body>
</html>

How Add Attributes to HTML Elements

Now, we want to use the category attribute as a class attribute in the HTML list:

<html>  
<body>

<h1>Bookstore</h1>

<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li class="{data($x/@category)}">{data($x/title)}</li>
}
</ul>

</body>
</html>

The XQuery expression above will generate the following result:

<html>
<body>
<h1>Bookstore</h1>

<ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class="WEB">Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul>

</body>
</html>