Latest web development tutorials

XQuery Adding elements and attributes

XML instance documents

In the following example we will continue to use this "books.xml" (same XML file and the section above is used) document.

See "books.xml" file in your browser .


Adding elements and attributes the results to

As seen in the previous section, we can cite in results input file elements and attributes:

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

XQuery expression above references title element and lang attributes in the result, like this:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>

Above XQuery expression returns the title elements of the way and in the same manner in the input document are described in them.

Now we want to add the results of our own elements and attributes!

Add HTML elements and text

Now, we want to add the results HTML element. We will result in a 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>

XQuery expression above will generate 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>

Adding attributes to HTML elements

Next, we should attribute category as an HTML list of class attributes to use:

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

XQuery expression above may generate 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>