0% found this document useful (0 votes)
3 views

Java XQuery

This Java program demonstrates how to use the Saxon library to execute an XQuery expression that retrieves book titles from an XML document named 'courses.xml'. It initializes a Processor, compiles the XQuery, sets the context item to the input XML document, and evaluates the query to print the titles. The program includes error handling for Saxon API exceptions.

Uploaded by

prathikaanand
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java XQuery

This Java program demonstrates how to use the Saxon library to execute an XQuery expression that retrieves book titles from an XML document named 'courses.xml'. It initializes a Processor, compiles the XQuery, sets the context item to the input XML document, and evaluates the query to print the titles. The program includes error handling for Saxon API exceptions.

Uploaded by

prathikaanand
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.io.

File;

import net.sf.saxon.s9api.*;

public class XQueryExample {

public static void main(String[] args) {


try {
// Create a Processor instance (this will be used to handle XQuery)
Processor processor = new Processor(false); // 'false' for non-
validation mode

// Create a XQueryCompiler
XQueryCompiler compiler = processor.newXQueryCompiler();

// Define your XQuery expression


String xqueryString = "for $book in doc('courses.xml')/books/book
return $book/title";

// Compile the XQuery expression


XQueryExecutable executable = compiler.compile(xqueryString);

// Create an XQueryEvaluator
XQueryEvaluator evaluator = executable.load();

// Set the input document (books.xml) for the XQuery evaluation


// Note: Ensure the 'books.xml' file is available or replace it with an
appropriate XML file path
File inputFile = new File("C:\\Users\\DELL\\Desktop\\Xquery\\
courses.xml");
XdmNode document = processor.newDocumentBuilder().build(inputFile);

// Set the document as the context for the query


evaluator.setContextItem(document);

// Execute the query and get the result


XdmValue result = evaluator.evaluate();

// Iterate through the result (which will be a sequence of titles)


for (XdmItem item : result) {
System.out.println(item.getStringValue());
}

} catch (SaxonApiException e) {
e.printStackTrace();
}
}
}

You might also like