XQuery Example

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
  


To Select Nodes From “books.xml”:

Functions:

To extract data from XML documents, the functions in XQuery are used.

Example:

doc("books.xml")

Explanation:

In the above example, we are opening the “books.xml” file using the doc() function.

Path Expressions:

To navigate through elements in an XML document, path expressions are used by XQuery.

Example:

doc("books.xml")/bookstore/book/title

Explanation:

In the above example, we are selecting all the title elements in the “books.xml” file using the above path expression. To select the bookstore element, we are using “/bookstore”, to select all the book elements under the bookstore element, we are using “/book” and to select all the title elements under each book element, we are using “/title”. Thus, the below will be extracted by the XQuery above:

ABC
XQuery Book
Sociology 1
Current Affairs
Science Book

Predicates:

To limit the extracted data from the XML documents, predicates are used by XQuery.

Example:

doc("books.xml")/bookstore/book[price>300]

Explanation:

In the above example, we are using the predicate to select all the book elements under the bookstore element with a price element having a value higher than 300. Thus, the below will be extracted by the XQuery above:

 
    Current Affairs
    Author Name
 2004
    500.00