XQuery Example

Toggle navigation
TUTORIAL HOME
XQuery Example
❮ Previous Next ❯
Let’s learn some basic XQuery by looking at an example.

The XML Example Document
We will use the following XML document in the examples below.

“books.xml”:

  Everyday Italian
  Giada De Laurentiis
  2005
  30.00

  Harry Potter
  J K. Rowling
  2005
  29.99

  XQuery Kick Start
  James McGovern
  Per Bothner
  Kurt Cagle
  James Linn
  Vaidyanathan Nagarajan
  2003
  49.99

  Learning XML
  Erik T. Ray
  2003
  39.95

View the “books.xml” file in your browser.

How to Select Nodes From “books.xml”?
Functions
XQuery uses functions to extract data from XML documents.

The doc() function is used to open the “books.xml” file:

doc(“books.xml”)
Path Expressions
XQuery uses path expressions to navigate through elements in an XML document.

The following path expression is used to select all the title elements in the “books.xml” file:

doc(“books.xml”)/bookstore/book/title
(/bookstore selects the bookstore element, /book selects all the book elements under the bookstore element, and /title selects all the title elements under each book element)

The XQuery above will extract the following:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
Predicates
XQuery uses predicates to limit the extracted data from XML documents.

The following predicate is used to select all the book elements under the bookstore element that have a price element with a value that is less than 30:

doc(“books.xml”)/bookstore/book[price<30]
The XQuery above will extract the following:

  Harry Potter
  J K. Rowling
  2005
  29.99

❮ Previous Next ❯

Leave a comment