Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XQuery adds elements and properties


May 28, 2021 XQuery


Table of contents


XQuery adds elements and properties

How does XQuery add elements and properties? Learn about it in this section.

XML instance documentation

We'll continue to use this "books.xml" document in the following example (the same XML file used in the previous section).

View the "books" file .xml your browser.


Add elements and properties to the result

As you can see in the previous section, we can refer to the elements and properties in the input file in the results:

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

The above XQuery expression refers to the title element and lang property in the result, as:

<title >Everyday Italian</title>
<title >Harry Potter</title>
<title >Learning XML</title>
<title >XQuery Kick Start</title>

The above XQuery expressions return title elements in the same way that they are described in the input document.

Now we're going to add our own elements and attributes to the results!

Add HTML elements and text

Now we're going to add HTML elements to the results. We'll put the results in an HTML list:

<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 above XQuery expression produces the following results:

<html>
<body>

<h1>Bookstore</h1>

<ul>
<li>Everyday Italian. Category: COOKING</li>
<li>Harry Potter. Category: CHILDREN</li>
<li>Learning XML. Category: WEB</li>
<li>XQuery Kick Start. Category: WEB</li>
</ul>

</body>
</html>

Add properties to HTML elements

Next, let's use the category property as the class property 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 produces the following results:

<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>

That's what you know about XQuery adding elements and properties.