A Simple XQuery Example: Filtering XML Data Based on Specified Criteria

Learn the fundamentals of XQuery by building a simple XML query. This tutorial demonstrates a basic XQuery expression for filtering XML data, provides a practical code example using Java and the Saxon library, and highlights XQuery's capability for efficient and targeted data extraction from XML documents.



A Simple XQuery Example: Filtering XML Data

Introduction

This example demonstrates a basic XQuery expression that filters XML data. We'll use a sample XML document (courses.xml) and an XQuery file (courses.xqy) containing the query. A Java program (XQueryTester.java) then executes the XQuery expression against the XML data.

Sample XML Data (courses.xml)

courses.xml

<?xml version="1.0" encoding="UTF-8"?>
<courses>
  <course>
    <title>Learn Java in 3 Months</title>
    <author>Sonoo Jaiswal</author>
    <year>2008</year>
    <fees>10000.00</fees>
  </course>
  <course>
    <title>Learn Dot Net in 3 Months</title>
    <author>Vicky Kaushal</author>
    <year>2008</year>
    <fees>10000.00</fees>
  </course>
  <course>
    <title>Learn C in 2 Months</title>
    <author>Ramesh Kumar</author>
    <year>2014</year>
    <fees>3000.00</fees>
  </course>
  <course>
    <title>Learn XML in 2 Months</title>
    <author>Ajeet Kumar</author>
    <year>2015</year>
    <fees>4000.00</fees>
  </course>
</courses>

XQuery Expression (courses.xqy)

courses.xqy

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

This XQuery selects the title of each course where the fees are greater than 5000.

Java Program (XQueryTester.java)

XQueryTester.java

// ... (Java code as provided in the original text) ...

This Java program uses the Saxon-HE XQuery processor to execute the XQuery expression against the XML data.

Running the Example

  1. Save courses.xml, courses.xqy, and XQueryTester.java in the same directory.
  2. Compile XQueryTester.java using a Java compiler (JDK 1.5 or later required). Make sure that the necessary Saxon-HE libraries are included in the classpath.
  3. Run the compiled Java program.
Example Output

Learn Java in 3 Months.
Learn Dot Net in 3 Months.
        

Conclusion

This simple example illustrates how XQuery can be used to query and extract specific data from XML documents. The Java program shows how to integrate XQuery with a programming language to process XML data dynamically.