XQuery First Example

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

XQuery First Example

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

courses.xml

  1. xml version="1.0" encoding="UTF-8"?>  
  2. <courses>     
  3.    <course category="JAVA">  
  4.       <title lang="en">Learn Java in 3 Months.title>  
  5.       <trainer>Sonoo Jaiswaltrainer>  
  6.       <year>2008year>  
  7.       <fees>10000.00fees>  
  8.    course>    
  9.     <course category="Dot Net">  
  10.       <title lang="en">Learn Dot Net in 3 Months.title>  
  11.       <trainer>Vicky Kaushaltrainer>  
  12.       <year>2008year>  
  13.       <fees>10000.00fees>  
  14.    course>  
  15.     <course category="C">  
  16.       <title lang="en">Learn C in 2 Months.title>  
  17.       <trainer>Ramesh Kumartrainer>  
  18.       <year>2014year>  
  19.       <fees>3000.00fees>  
  20.    course>  
  21.     <course category="XML">  
  22.       <title lang="en">Learn XML in 2 Months.title>  
  23.       <trainer>Ajeet Kumartrainer>  
  24.       <year>2015year>  
  25.       <fees>4000.00fees>  
  26.    course>    
  27. courses>

courses.xqy

  1. for $x in doc("courses.xml")/courses/course  
  2. where $x/fees>5000  
  3. return $x/title  

This example will display the title elements of the courses whose fees are greater than 5000.

Create a Java based XQuery executor program to read the courses.xqy, passes it to the XQuery expression processor, and executes the expression. After that the result will be displayed.

XQueryTester.java

 

Execute XQuery against XML

Put the above three files to a same location. We put them on desktop in a folder name XQuery2. Compile XQueryTester.java using console. You must have JDK 1.5 or later installed on your computer and classpaths are configured.

Compile:

javac XQueryTester.java

Execute:

java XQueryTester

Output:

XQUERY First example 1