XQuery Add

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

XQuery Add

XQuery Add is used for adding elements, attributes, HTML elements and text in the results from the input documents.

Let's understand it by using an example.

XQuery Add Example

Take an XML file named books.xml, having the following data.

books.xml

  1. <bookstore>  
  2. <book category="Mythology">  
  3. <title lang="en">Immortals of Meluhatitle>  
  4. <author>Amishauthor>  
  5. <year>2010year>  
  6. <price>180price>  
  7. book>  
  8. <book category="Children">  
  9. <title lang="en">Harry Pottertitle>  
  10. <author>J K. Rowlingauthor>  
  11. <year>2005year>  
  12. <price>300price>  
  13. book>  
  14. <book category="Programming">  
  15. <title lang="en">Let's Ctitle>  
  16. <author>Yashwant Kanetkarauthor>  
  17. <year>2003year>  
  18. <price>200price>  
  19. book>  
  20. bookstore>  

XQuery Expression

books.xqy

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

Now this XQuery expression will return the title elements in the same manner as they are described in the input document.

Output:

 

XQuery Add

 

Now you can add your own elements and attributes to the result.

Add HTML Elements and Text

If you want to add some HTML elements to the result, use the XQuery like this:

book.xqy:

  1. <html>  
  2. <body>  
  3.   
  4. <h1>Bookstoreh1>  
  5. <ul>  
  6. {  
  7. for $x in doc("books.xml")/bookstore/book  
  8. order by $x/title  
  9. return <li>{data($x/title)}. Category: {data($x/@category)}li>  
  10. }  
  11.   
  12. ul>  
  13. body>  
  14. html>  

XQuery Add2