Home >>XQuery Tutorial >XQuery First Example

XQuery First Example

XQuery First Example

Here, the XML document is named as books.xml and xqy file is named as books.xqy


<?xml version="1.0" encoding="UTF-8"?>  
   <course category="JAVA">  
      <title lang="en">Learn HTML in 3 Months.</title>  
    <course category="Dot Net">  
      <title lang="en">Learn PHP in 3 Months.</title>  
    <course category="C">  
      <title lang="en">Learn SEO in 2 Months.</title>  
      <trainer>Rahul </trainer>  
    <course category="XML">  
      <title lang="en">Learn XML in 2 Months.</title>  
      <trainer>Ajay </trainer>  

Following is a sample Xquery document containing the query expression to be executed on the above XML document. The objective is to get the title elements of those XML nodes where the price is greater than 30.


for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title


<title lang="en">Learn PHP in 24 hours</title>

<title lang="en">Learn XQuery in 24 hours</title>

Verify Result

To validate the result, substitute the contents of books.xqy (given in the Framework Setup chapter) with the above XQuery expression and execute the XQueryTester java program.

XQuery Expressions

Let us understand each piece of the above XQuery expression.

Use of functions


doc() is one of the XQuery functions that is used to locate the XML source. Here we've passed "books.xml". Given the relative path, books.xml will sit along the same route where books.xqy is current.

Use of XPath expressions


XQuery uses XPath expressions heavily to locate the required portion of XML on which search is to be made. Here we've selected all the book nodes accessible under books node.

Iterate the objects

for $x in doc("books.xml")/books/book

XQuery handles xml data as objects. In the above case, $x represents the chosen node, while the for loop iterates through the set of nodes.

Apply the condition

where $x/price>30

As $x represents the selected node, "/" is used to get the value of the specified element; "where" clause is used to place a condition on the search results.

Return the result

return $x/title