||This article has an unclear citation style. (March 2014)|
|This article needs additional citations for verification. (August 2010)|
|Stable release||2.0 / 2007-01-23|
|Influenced by||XSLT, XPointer|
|Influenced||XML Schema, XForms|
XPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document. XPath was defined by the World Wide Web Consortium (W3C).
- 1 Overview
- 2 Syntax and semantics (XPath 1.0)
- 3 Syntax and semantics (XPath 2.0)
- 4 Examples
- 5 Implementations
- 6 Use in schema languages
- 7 See also
- 8 References
- 9 External links
The XPath language is based on a tree representation of the XML document, and provides the ability to navigate around the tree, selecting nodes by a variety of criteria. In popular use (though not in the official specification), an XPath expression is often referred to simply as "an XPath".
Originally motivated by a desire to provide a common syntax and behavior model between XPointer and XSLT, subsets of the XPath query language are used in other W3C specifications such as XML Schema, XForms and the Internationalization Tag Set (ITS).
XPath has been adopted by a number of XML processing libraries and tools, many of which also offer CSS Selectors, another W3C standard, as a simpler alternative to XPath.
There are currently three versions of XPath in use. The latest version of the language (as at 10 April 2014) is 3.0, but XPath 1.0 is the version that is most widely available.
- XPath 2.0 became a Recommendation on 23 January 2007. A number of implementations exist but are not as widely used as XPath 1.0. The XPath 2.0 language specification is much larger than XPath 1.0 and changes some of the fundamental concepts of the language such as the type system.
- The most notable change is that XPath 2.0 is built around the XQuery and XPath Data Model which has a much richer type system. Every value is now a sequence (a single atomic value or node is regarded as a sequence of length one). XPath 1.0 node-sets are replaced by node sequences, which may be in any order.
- To support richer type sets, XPath 2.0 offers a greatly expanded set of functions and operators.
- XPath 2.0 is in fact a subset of XQuery 1.0. They share the same data model (XDM). It offers a
forexpression which is a cut-down version of the "FLWOR" expressions in XQuery. It is possible to describe the language by listing the parts of XQuery that it leaves out: the main examples are the query prolog, element and attribute constructors, the remainder of the "FLWOR" syntax, and the
- XPath 3.0 became a Recommendation on 8 April 2014. The most significant new feature is support for functions as first-class values. For details about what's new about XPath 3.0, see XPath 3.0 is a subset of XQuery 3.0, and most current implementations (April 2014) exist as part of an XQuery 3.0 engine.
Syntax and semantics (XPath 1.0)
The most important kind of expression in XPath is a location path. A location path consists of a sequence of location steps. Each location step has three components:
An XPath expression is evaluated with respect to a context node. An Axis Specifier such as 'child' or 'descendant' specifies the direction to navigate from the context node. The node test and the predicate are used to filter the nodes specified by the axis specifier: For example the node test 'A' requires that all nodes navigated to must have label 'A'. A predicate can be used to specify that the selected nodes have certain properties, which are specified by XPath expressions themselves.
The XPath syntax comes in two flavours: the abbreviated syntax, is more compact and allows XPaths to be written and read easily using intuitive and, in many cases, familiar characters and constructs. The full syntax is more verbose, but allows for more options to be specified, and is more descriptive if read carefully.
The compact notation allows many defaults and abbreviations for common cases. Given source XML containing at least
<A> <B> <C/> </B> </A>
the simplest XPath takes a form such as
which selects C elements that are children of B elements that are children of the A element that forms the outermost element of the XML document. The XPath syntax is designed to mimic URI (Uniform Resource Identifier) and Unix-style file path syntax.
More complex expressions can be constructed by specifying an axis other than the default 'child' axis, a node test other than a simple name, or predicates, which can be written in square brackets after any step. For example, the expression
selects the first element ('
'), whatever its name ('
*'), that is a child ('
/') of a B element that itself is a child or other, deeper descendant ('
//') of an A element that is a child of the current context node (the expression does not begin with a '
/'). If there are several suitable B elements in the document, this actually returns a set of all their first children. ("
(A//B/*)" returns just the first such node.)
In the full, unabbreviated syntax, the two examples above would be written
Here, in each step of the XPath, the axis (e.g.
descendant-or-self) is explicitly specified, followed by
:: and then the node test, such as
node() in the examples above.
Axis specifiers indicate navigation direction within the tree representation of the XML document. The axes available are:
|Full Syntax||Abbreviated Syntax||Notes|
As an example of using the attribute axis in abbreviated syntax,
//a/@href selects the attribute called
a elements anywhere in the document tree. The expression . (an abbreviation for self::node()) is most commonly used within a predicate to refer to the currently selected node. For example,
h3[.='See also'] selects an element called
h3 in the current context, whose text content is
Node tests may consist of specific node names or more general expressions. In the case of an XML document in which the namespace prefix
gs has been defined,
//gs:enquiry will find all the
enquiry elements in that namespace, and
//gs:* will find all elements, regardless of local name, in that namespace.
Other node test formats are:
- finds an XML comment node, e.g.
<!-- Comment -->
- finds a node of type text, e.g. the
- finds XML processing instructions such as
<?php echo $a; ?>. In this case,
- finds any node at all.
Predicates, written as expressions in square brackets, can be used to restrict a node-set to select only those nodes for which some condition is true. For example
a[@href='help.php'] will select those
a elements (among the children of the context node) having an
href attribute whose value is
There is no limit to the number of predicates in a step, and they need not be confined to the last step in an XPath. They can also be nested to any depth. Paths specified in predicates begin at the context of the current step (i.e. that of the immediately preceding node test) and do not alter that context. All predicates must be satisfied for a match to occur.
When the value of the predicate is numeric, it is interpreted as a test on the position of the node. So
p selects the first
p element child, while
p[last()] selects the last.
In other cases, the value of the predicate is automatically converted to a boolean. When the predicate evaluates to a node-set, the result is true when the node-set is non-empty. Thus
p[@x] selects those
p elements that have an attribute named
A more complex example: the expression
a[/html/@lang='en'][@href='help.php']/@target selects the value of the
target attribute of the first
a element among the children of the context node that has its
href attribute set to
help.php, provided the document's
html top-level element also has a
lang attribute set to
en. The reference to an attribute of the top-level element in the first predicate affects neither the context of other predicates nor that of the location step itself.
Predicate order is significant if predicates test the position of a node. Each predicate 'filters' a location step's selected node-set in turn. So
a[@href='help.php'] will find a match only if the first
a child of the context node satisfies the condition
a[@href='help.php'] will find the first
a child that satisfies this condition.
Functions and operators
XPath 1.0 defines four data types: node-sets (sets of nodes with no intrinsic order), strings, numbers and booleans.
The available operators are:
- The "/", "//" and "[...]" operators, used in path expressions, as described above.
- A union operator, "|", which forms the union of two node-sets.
- Boolean operators "and" and "or", and a function "not()"
- Arithmetic operators "+", "-", "*", "div" (divide), and "mod"
- Comparison operators "=", "!=", "<", ">", "<=", ">="
The function library includes:
- Functions to manipulate strings: concat(), substring(), contains(), substring-before(), substring-after(), translate(), normalize-space(), string-length()
- Functions to manipulate numbers: sum(), round(), floor(), ceiling()
- Functions to get properties of nodes: name(), local-name(), namespace-uri()
- Functions to get information about the processing context: position(), last()
- Type conversion functions: string(), number(), boolean()
Some of the more commonly useful functions are detailed below. For a complete description, see the W3C Recommendation document
Node set functions
- returns a number representing the position of this node in the sequence of nodes currently being processed (for example, the nodes selected by an xsl:for-each instruction in XSLT).
- returns the number of nodes in the node-set supplied as its argument.
- converts any of the four XPath data types into a string according to built-in rules. If the value of the argument is a node-set, the function returns the string-value of the first node in document order, ignoring any further nodes.
- concat(string, string, string*)
- concatenates two or more strings
- starts-with(s1, s2)
- contains(s1, s2)
- substring(string, start, length?)
- substring-before(s1, s2)
- substring-after(s1, s2)
- returns number of characters in string
- all leading and trailing whitespace is removed and any sequences of whitespace characters are replaced by a single space. This is very useful when the original XML may have been prettyprint formatted, which could make further string processing unreliable.
- returns a
lengthcharacters long substring of the given
string, starting at
start(which begins with
- negates any boolean expression.
- evaluates to true.
- evaluates to false.
- converts the string values of all the nodes found by the XPath argument into numbers, according to the built-in casting rules, then returns the sum of these numbers.
Expressions can be created inside predicates using the operators:
=, !=, <=, <, >= and
>. Boolean expressions may be combined with brackets
() and the boolean operators
or as well as the
not() function described above. Numeric calculations can use
*, +, -, div and
mod. Strings can consist of any Unicode characters.
//item[@price > 2*@discount] selects items whose price attribute is greater than twice the numeric value of their discount attribute.
Entire node-sets can be combined ('unioned') using the vertical bar character |. Node sets that meet one or more of several conditions can be found by combining the conditions inside a predicate with '
v[x or y] | w[z] will return a single node-set consisting of all the
v elements that have
y child-elements, as well as all the
w elements that have
z child-elements, that were found in the current context.
Syntax and semantics (XPath 2.0)
Given a sample XML document
<?xml version="1.0" encoding="utf-8"?> <wikimedia> <projects> <project name="Wikipedia" launch="2001-01-05"> <editions> <edition language="English">en.wikipedia.org</edition> <edition language="German">de.wikipedia.org</edition> <edition language="French">fr.wikipedia.org</edition> <edition language="Polish">pl.wikipedia.org</edition> <edition language="Spanish">es.wikipedia.org</edition> </editions> </project> <project name="Wiktionary" launch="2002-12-12"> <editions> <edition language="English">en.wiktionary.org</edition> <edition language="French">fr.wiktionary.org</edition> <edition language="Vietnamese">vi.wiktionary.org</edition> <edition language="Turkish">tr.wiktionary.org</edition> <edition language="Spanish">es.wiktionary.org</edition> </editions> </project> </projects> </wikimedia>
The XPath expression
selects name attributes for all projects, and
selects all editions of all projects, and
selects addresses of all English Wikimedia projects (text of all edition elements where language attribute is equal to English). And the following
selects addresses of all Wikipedias (text of all edition elements that exist under project element with a name attribute of Wikipedia)
- Command-line tools
- RaptorXML Server from Altova supports XPath 1.0, 2.0, and 3.0
- Implementations for database engines
- Saxon XSLT supports XPath 1.0 and XPath 2.0 (as well as XSLT 1.0, XSLT 2.0, and XQuery 1.0)
- BaseX (also supports XPath 2.0 and XQuery)
- Sedna XML Database Both XML:DB and proprietary.
- QuiXPath a streaming Open Source implementation by Innovimax
The Java package
javax.xml.xpath has been part of Java standard edition since Java 5. Technically this is an XPath API rather than an XPath implementation, and it allows the programmer the ability to select a specific implementation that conforms to the interface.
- The ElementTree XML API in the Python Standard Library includes limited support for XPath expressions
- Sedna XML Database
- MySQL supports a subset of XPath from version 5.1.5 onwards
- PostgreSQL supports XPath and XSLT from version 8.4 on
- The tdom package provides "a very complete, compliant and fast XPath implementation in C"
Use in schema languages
XPath is increasingly used to express constraints in schema languages for XML.
- The (now ISO standard) schema language Schematron pioneered the approach.
- A streaming subset of XPath is used in W3C XML Schema 1.0 for expressing uniqueness and key constraints. In XSD 1.1, the use of XPath is extended to support conditional type assignment based on attribute values, and to allow arbitrary boolean assertions to be evaluated against the content of elements.
- XForms uses XPath to bind types to values.
- The approach has even found use in non-XML applications, such as the constraint language for Java called PMD: the Java is converted to a DOM-like parse tree, then XPaths rules are defined over the tree.
- XPath 2.0
- XSL, XSLT, XSL-FO
- XLink, XPointer
- XML Schema
- Navigational database
- XML database
- "XML and Semantic Web W3C Standards Timeline". 2012-02-04.
- Bergeron, Randy (October 31, 2000). "XPath—Retrieving Nodes from an XML Document". SQL Server Magazine.
- Pierre Geneves (October 2012). "Course: The XPath Language".
- XPath 2.0 supports atomic types, defined as built-in types in XML Schema, and may also import user-defined types from a schema.
- XPath 3.0 W3C Recommendation
- What's new in 3.0 (XSLT/XPath/XQuery) (plus XML Schema 1.1) by Michael Kay, Saxonica
- Online docs at postgresql.org
|Wikibooks has more on the topic of: XPath|
- XPath 1.0 specification
- XPath 2.0 specification
- What's New in XPath 2.0
- XPath Reference (MSDN)
- XPath Expression Syntax (Saxon)
- XPath 2.0 Expression Syntax (Saxon), 
- XPath - MDC Docs by Mozilla Developer Network
- XPath introduction/tutorial
- XSLT and XPath function reference