Skip to content
Related Articles

Related Articles

XQuery | Installation and Example

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 25 Jan, 2022
View Discussion
Improve Article
Save Article

XQuery: XQuery is the language for querying XML data. It is used to retrieve information stored in XML format. XQuery for XML is similar as SQL for databases. It can be used on XML Databases, relational databases containing data in XML formats or XML documents. XQuery was designed by W3C and it first appeared in 2007. It is a W3C recommendation from April 8, 2014 which is supported by all major databases.
Uses of Xquery: 

  • Extracting information from database that is to be used in Web services like SoapUI.
  • Receiving data form database that is to be used with application integration.
  • To generate summary reports.
  • To retrieve relevant information from XML files.

Installation and Example: 

  1. Download Saxon jar file.
  2. Extract the zip file and copy all jar files to java_base_path/JRE/lib/ext.
  3. Now create a XML file with the following code and name it as “article.xml”. 


<?xml version="1.0" encoding="UTF-8"?>
   <article category="JAVA">
      <title>Introduction to Java</title>
   <article category="Python">
      <title>Introduction to Python</title>
   <article category="XML">
      <title>Introduction to XML</title>
   <article category="HTML">
      <title>Introduction to HTML</title>

Now create a java file with any name of your choice( in my case) and add the following code in the same. 


import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import com.saxonica.xqj.SaxonXQDataSource;
class example {
    public static void main(String[] args)
        try {
        catch (Exception e) {
    private static void solve() throws
            FileNotFoundException, XQException {
        InputStream inputStream =
            new FileInputStream(new File("articles.xqy"));
        XQDataSource ds = new SaxonXQDataSource();
        XQConnection conn = ds.getConnection();
        XQPreparedExpression exp =
        XQResultSequence result = exp.executeQuery();
        while ( {

Note: Save the file with .java extension in the same directory as that of article.xml.

Create an XQuery file with the name “articles.xqy” with the following code and save it in the same directory as that of article.xml. 

for $x in doc("article.xml")/articles/article
return $x/title

Now open Command prompt in the same folder where article.xml is located and enter the following command there. 

java example

As it could be seen in the output it will print the title of all the article’s data stored in the XML file. 

Now, You have successfully executed your first XQuery code. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!