XPath Examples
This topic reviews the syntax examples that appear throughout the XPath Reference. All are based on the Sample XML File for XPath Syntax (inventory.xml). For an example of using an XPath expression in a test file, see "Example of Unions ( | )", at the bottom of this topic.
Expression | Refers to |
---|---|
|
All |
|
All |
|
All |
|
The document element ( |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All elements that are the children of |
|
All |
|
All grandchildren elements of the current context. |
|
All elements with the |
|
The |
|
The |
|
Returns an empty node set, because attributes do not contain element children. This expression is allowed by the XML Path Language (XPath) grammar, but is not strictly valid. |
|
All |
|
The |
|
All attributes of the current element context. |
|
All |
|
All |
|
The first |
|
The third |
|
The |
|
All elements from the |
|
All attributes from the |
Note that indexes are relative to the parent. Consider the following data:
<x>
<y/>
<y/>
</x>
<x>
<y/>
<y/>
</x>
Expression | Refers to |
---|---|
|
The first |
|
The first |
|
The first |
|
The second |
The remaining examples refer to the Sample XML file for XPath.
Expression | Refers to |
---|---|
|
The last |
|
The last |
|
The last |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
All |
|
The first three books (1, 2, 3). |
|
All |
|
All |
|
all author elements containing any child element whose value is |
|
All |
|
All |
|
The first two |
|
The second text node in each |
|
The nearest |
|
The nearest |
|
The nearest |
Example of Unions ( | )
To demonstrate the union operation, we use the following XPath expression:
x | y/x
selects all the <x> elements whose values are green or blue in the following XML file:
XML File (data1.xml)
XSLT File (union.xsl)
Formatted Output
green,blue,blue,green
Processor Output
<?xml version="1.0" encoding="UTF-16"?>green,blue,blue,green