Last modified on 2 June 2014, at 17:55

XQuery/Quantified Expressions

MotivationEdit

You have a list of items in a sequence and you want to test to see if any or all of the items match a condition. The result of the test on the sequence will be either true or false.

MethodEdit

Quantified expressions have a format very similar to a FLWOR expression with the the following two changes

  1. instead of the word for you will use either the words some or every
  2. instead of the where/order/return you will use the word satisfies

The quantified expression always takes a sequence as its input and returns a boolean true/false as its output.

Here is an example of a quantified expression which checks to see if there are any books that contain the word "cat".

Assume you have a collection of books, each book has a single XML file with a title attribute such as this:

<book>
   ...
   <title>The Cat With Nine Lives</title>
   ...
</book>

Examples of Quantified ExpressionsEdit

The XQuery expression to limit books with the string "cat" somewhere in the title would be:

Test for at least one "cat book" in a collection of books

some $book in collection($collection)/book
satisfies (contains(lower-case($book/title), 'cat'))

This expression will return true as long as one book contains the word "cat" in the title.

Test for that all books are cat books

every $book in collection($collection)/book
satisfies (contains(lower-case($book/title), 'cat'))

This expression will return true only if ALL books contain the string "cat" in the title.

Note that the quantified expression can not be used to indicate which book title contains the word "cat", only that the word "cat" occurs in at least one title in your collection.

Quantified expressions can often be rewritten by a single XPath expression with a predicate. In the above case the expression would be:

let $has-a-cat-book := exists(collection($collection)/book/title[contains(lower-case(., 'cat')])

The variable $has-a-cat-book will be set to true() if any book contains the word "cat".

Some XQuery parsers can optimize quantified expressions better and some people feel that quantified expressions are more readable then a single XPath expression.