Collections
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.
./first-name
first-name
Find all unqualified book elements.
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.
author[0]
The following finds the third author element that has a first name.
author[first-name][2]
Note that indexes are relative to the parent. Consider the following data.
<x>
<y/>
<y/>
</x>
<x>
<y/>
<y/>
</x>
Find the first y from each x.
x/y[0]
Find the first y from the entire set of y elements within x elements.
(x/y)[0]
Find the first y from the first x.
x[0]/y[0]
Finding the Last Element in a Collection
The last function returns True for the last element in a collection. Note that last is relative to the parent node.
Examples
Find the last book.
book[last()]
Find the last author for each book.
book/author[last()]
Find the last author from the entire set of authors of books.
(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.