Important:
This is retired content. This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
A version of this page is also available for
4/8/2010

Collections returned by XML Path Language (XPath) queries preserve document order, hierarchy, and identity, to the extent that these are defined. That is, a collection of elements is returned in document order without repeated elements. Because by definition attributes are unordered, there is no implicit order to attributes returned for a specific element.

The collection of all elements with a certain tag name is expressed using the tag name itself. This can be qualified by showing that the elements are selected from the current context by using a period and forward slash (./), but the current context is used by default and does not have to be noted explicitly.

Examples

Find all first-name elements. These following examples are equivalent.

Copy Code
./first-name
first-name

Find all unqualified book elements.

Copy Code
book

Indexing into a Collection

XPath expressions make it easy to find a specific node within a set of nodes. Simply enclose the index ordinal within square brackets. The ordinal is zero-based (the first element is number zero).

The bracket characters [] have higher precedence than the slash characters / and //. The expression "//comment()[3]" is interpreted as "//(comment()[3])", and selects all comments with an index equal to 3 relative to the comment's parent anywhere in the document. This differs from the expression "(//comment())[3]", which selects the third comment from the set of all comments relative to the parent. The first expressions can return more than one comment, while the other expression can return only one comment.

Examples

The following finds the first author element.

Copy Code
author[0]

The following finds the third author element that has a first name.

Copy Code
author[first-name][2]

Note that indexes are relative to the parent. Consider the following data.

Copy Code
<x>
  <y/>
  <y/>
</x>
<x>
  <y/>
  <y/>
</x>

Find the first y from each x.

Copy Code
x/y[0]

Find the first y from the entire set of y elements within x elements.

Copy Code
(x/y)[0]

Find the first y from the first x.

Copy Code
x[0]/y[0]

Finding the Last Element in a Collection

The lastfunction returns True for the last element in a collection. Note that lastis relative to the parent node.

Examples

Find the last book.

Copy Code
book[last()]

Find the last author for each book.

Copy Code
book/author[last()]

Find the last author from the entire set of authors of books.

Copy Code
(book/author)[last()]

Grouping

Parentheses can be used to group collection operators for clarity or where the usual precedence is inadequate to express an operation.

See Also