XQuery Adding Elements and Attributes

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
 <year>2005</year>
    <price>300.00</price>
  </book>
 
  <book category="Sociology">
    <title lang="en">Sociology 1</title>
    <author>Author Name</author>
 <year>2010</year>
    <price>250.00</price>
  </book>
 
  <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
 <year>2004</year>
    <price>500.00</price>
  </book>
 
  <book category="Science">
    <title lang="en">Science Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>
 <year>2011</year>
    <price>150.00</price>
  </book>
 
</bookstore>

Adding Elements and Attributes to the Result:

The elements and attributes can be added in the result from the input document (“books.xml).

Example:

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

Explanation:

In the above example, we are using an XQuery expression to include both the title element and the lang attribute in the result. The title elements are thus returned in the same way as they are described in the input document. Here, we are returning the title elements in alphabetical order.

Result:

<title lang="en">ABC</title>
<title lang="en">Current Affairs</title>
<title lang="en">Science Book</title>
<title lang="en">Sociology 1</title>
<title lang="en">XQuery Book</title>

Add HTML Elements and 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>

Explanation:

In the above example, we are adding some HTML elements to the result. In an HTML list, we will put the result together with some text.

Result:

<html>
<body>
 
<h1>Bookstore</h1>
 
<ul>
<li>ABC. Category: CHILD</title></li>
<li>XQuery Book. Category: IT</title></li>
<li>Sociology 1. Category: SOCIOLOGY</title></li>
<li>Current Affairs. Category: GK</title></li>
<li>Science Book. Category: SCIENCE</title></li>
</ul>
 
</body>
</html>

Add Attributes to the HTML Elements:

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

Explanation:

In the above example, we are using the category attribute as a class attribute in the HTML list.

Result:

<html>
<body>
<h1>Bookstore</h1>
 
<ul>
<li class="CHILD">ABC</li>
<li class="IT">XQuery Book</li>
<li class="SOCIOLOGY">Sociology 1</li>
<li class="GK">Current Affairs</li>
<li class="SCIENCE">Science Book</li>
</ul>
 
</body>
</html>
Please Share