xml
  1. xml-xquery-first-example

XML XQuery First Example

Syntax

The basic syntax of an XQuery program is as follows:

xquery version "3.1";

(: declare namespace declaration(s) :)

(: declare variable declaration(s) :)

(: main query :)

(: function declaration(s) :)

Example

Here is a simple example of an XQuery program that retrieves all of the book titles from an XML file:

xquery version "3.1";

(: declare the namespace for the XML file :)
declare namespace bookstore = "http://example.com/bookstore";

(: main query to retrieve all book titles :)
for $x in /bookstore:bookstore/bookstore:book
return $x/bookstore:title

Output

The output of the above example will be a list of all book titles in the XML file:

XML and Java - Developing Web Applications
XML Pocket Reference

Explanation

  • The xquery version "3.1"; statement declares the XQuery version being used in the program.
  • The declare namespace statement declares the namespace of the XML file being used in the program.
  • The for $x in /bookstore:bookstore/bookstore:book statement is the main query that retrieves all book titles from the XML file.
  • The return $x/bookstore:title statement returns the book title from each book element.

Use

It can be modified to retrieve different elements or attributes of the XML file based on specific requirements.

Important Points

  • XQuery is used to query and retrieve data from XML and JSON files.
  • The XQuery program must declare the XQuery version being used.
  • The XQuery program must declare the namespace of the XML or JSON file being queried.
  • The main query is used to retrieve specific data from the XML or JSON file.

Summary

This tutorial covered the basic syntax of an XQuery program and provided a simple example of how to retrieve specific data from an XML file using XQuery. It also explained the importance of declaring the XQuery version and namespace in the program.

Published on: