XQuery Example

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>

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:

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

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:

 <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
 <year>2004</year>
    <price>500.00</price>
  </book>
Please Share