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

courses.xml


<?xml version="1.0" encoding="UTF-8"?>  
<courses>     
   <course category="JAVA">  
      <title lang="en">Learn HTML in 3 Months.</title>  
      <trainer>amit</trainer>  
      <year>2010</year>  
      <fees>8000.00</fees>  
   </course>    
    <course category="Dot Net">  
      <title lang="en">Learn PHP in 3 Months.</title>  
      <trainer>Vishal</trainer>  
      <year>2010</year>  
      <fees>12000.00</fees>  
   </course>  
    <course category="C">  
      <title lang="en">Learn SEO in 2 Months.</title>  
      <trainer>Rahul </trainer>  
      <year>2013</year>  
      <fees>5000.00</fees>  
   </course>  
    <course category="XML">  
      <title lang="en">Learn XML in 2 Months.</title>  
      <trainer>Ajay </trainer>  
      <year>2018</year>  
      <fees>4500.00</fees>  
   </course>    
</courses>  


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.

books.xqy

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

Result

<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("books.xml")

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

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

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

No Sidebar ads