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:
Xml | /IMG>Copy Code |
---|---|
<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)
Xml | /IMG>Copy Code |
---|---|
<?xml version='1.0'?><?xml-stylesheet type="text/xsl" href="union.xsl"?><root> <x>green</x> <y> <x>blue</x> <x>blue</x> </y> <z> <x>red</x> <x>red</x> </z> <x>green</x></root> |
XSLT File (union.xsl)
Xml | /IMG>Copy Code |
---|---|
<?xml version='1.0'?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="root"> <xsl:for-each select="x | y/x"> <xsl:value-of select="."/>, <xsl:if test="not(position()=last())">,</xsl:if> </xsl:for-each></xsl:template> </xsl:stylesheet> |
Formatted Output
green,blue,blue,green
Processor Output
<?xml version="1.0" encoding="UTF-16"?>green,blue,blue,green