XQuery Adding Elements and Attributes

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
 2005
    300.00
  

  
    Sociology 1
    Author Name
 2010
    250.00
  

  
    Current Affairs
    Author Name
 2004
    500.00
  

  
    Science Book
    Author 1
    Author 2
    Author 3
 2011
    150.00
  


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:

ABC
Current Affairs
Science Book
Sociology 1
XQuery Book

Add HTML Elements and Text:




Bookstore

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

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:




Bookstore

  • ABC. Category: CHILD
  • XQuery Book. Category: IT
  • Sociology 1. Category: SOCIOLOGY
  • Current Affairs. Category: GK
  • Science Book. Category: SCIENCE

Add Attributes to the HTML Elements:




Bookstore

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

Explanation:

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

Result:



Bookstore

  • ABC
  • XQuery Book
  • Sociology 1
  • Current Affairs
  • Science Book