XQuery/XPath examples

Motivation
You would like to select specific structures within an XML document. You would like to use a language that is consistent across all W3C XML Standards. This language is XPath.

Sample Input File
Put this file in /db/apps/training/data/books.xml

XPath provides a number of functions and axes to move around an XML structure.

Sample Test XQuery Script
Here is a sample XQuery "driver" for these tests. To use it just replace the function after the return on the last line.

Screen Image of XQuery Results in oXygen
There are several ways to test your XPath expressions. One of the most useful is to put your XML test data in document within eXist and then use a tool such as oXygen to execute the test on the server but then display the results in the oXygen results window. This can be done within oXygen by setting up eXist (not the default internal Saxon) as your "transformation scenario".

The following is a screen image of how these results look when viewed with the oXygen IDE:



Sample XPath Expressions
Return the entire data file

$books

Get just books and all the data for each book.

$books//book

Get all the book titles

$books//title

Get the collection description

$books/description/text

Get the descriptions for all the books

$books//book/description/text

Counting and Math
Count the number of books using a absolute path

count($books/book) (: should return 5 :)

Count the number of books using //. With eXist executes much faster on larger collections.

count($books//book) (: should return 5 :)

Get a sequence of all the titles in the book collection.

$books//title/text

Calculate the total and average price of all the books in the collection.

sum($books//list-price/text) (: Should return a number such as 171.8 :) avg($books//list-price/text) (: Should return a number such as 34.36 :) min($books//list-price/text) (: Should return a number such as 29.95 :) max($books//list-price1/text) (: Should return a number such as 49.95 :)

The following scripts show some of these functions and axes in use.

Adding Predicates
A predicate is a qualifier that is added to the end of an XPath expression. It is usually used to filter out nodes from result set. Predicates are similar to WHERE constructs in SQL.

Get all the wikibooks

$books//book[format='Wikibook']

Get just the titles of the wikibooks

$books//book[format='Wikibook']/title/text

Get all the books that contain the word "XQuery" somewhere in the title

$books//book[contains(title, 'XQuery')]/title/text

Complex Predicates

 * 1) node
 * 2) text
 * 3) string(..)
 * 4) data(..)
 * 5) child::
 * 6) parent::
 * 7) following-sibling::
 * 8) preceding-sibling::
 * 9) descendant::
 * 10) descendant-or-self
 * 1) descendant-or-self

Navigating around a tree with distinct tags

Navigating around a tree with a single tag