Xpath Tutorial
Xpath Tutorial
XPath Functions
Table of Contents
XPath Introduction
This chapter explains what XPath is.
XPath Nodes
This chapter defines the different types of nodes in XPath and the relationship of nodes.
XPath Syntax
This chapter explains the XPath syntax.
XPath Axes
This chapter explains the XPath axes.
XPath Operators
This chapter lists the operators that can be used in XPath expressions.
XPath Examples
This chapter uses the "books.xml" document to demonstrate some XPath examples.
XPath Summary
This chapter contains a summary on what you have learned in this tutorial and a
recommendation on what subject you should study next.
« W3Schools Home Next Chapter »
XPath Introduction
« Previous Next Chapter »
HTML / XHTML
XML / XML Namespaces
If you want to study these subjects first, find the tutorials on our Home page.
What is XPath?
XQuery and XPointer are both built on XPath expressions. XQuery 1.0 and XPath 2.0 share the
same data model and support the same functions and operators.
XPath was designed to be used by XSLT, XPointer and other XML parsing software.
To read more about the XPATH activities at W3C, please read our W3C tutorial.
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
XPath Nodes
« Previous Next Chapter »
XPath Terminology
Nodes
In XPath, there are seven kinds of nodes: element, attribute, text, namespace,
processing-instruction, comment, and document nodes.
XML documents are treated as trees of nodes. The topmost element of the tree is called
the root element.
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Atomic values
J K. Rowling
"en"
Items
Relationship of Nodes
Parent
In the following example; the book element is the parent of the title, author, year, and
price:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Children
In the following example; the title, author, year, and price elements are all children of
the book element:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Siblings
In the following example; the title, author, year, and price elements are all siblings:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Ancestors
In the following example; the ancestors of the title element are the book element and the
bookstore element:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Descendants
In the following example; descendants of the bookstore element are the book, title,
author, year, and price elements:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
XPath Syntax
« Previous Next Chapter »
XPath uses path expressions to select nodes or node-sets in an XML document. The
node is selected by following a path or steps.
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected
by following a path or steps. The most useful path expressions are listed below:
Expression Description
nodename Selects all child nodes of the named node
/ Selects from the root node
// Selects nodes in the document from the current node that match
the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes
In the table below we have listed some path expressions and the result of the
expressions:
Predicates
Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of
the expressions:
Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind
In the table below we have listed some path expressions and the result of the
expressions:
Path Expression Result
/bookstore/* Selects all the child nodes of the bookstore element
//* Selects all elements in the document
//title[@*] Selects all title elements which have any attribute
In the table below we have listed some path expressions and the result of the
expressions:
XPath Reference
XPath Functions
XPath Axes
« Previous Next Chapter »
The XML Example Document
We will use the following XML document in the examples below.
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
XPath Axes
An axis defines a node-set relative to the current node.
AxisName Result
An absolute location path starts with a slash ( / ) and a relative location path does not. In
both cases the location path consists of one or more steps, each separated by a slash:
/step/step/...
step/step/...
an axis (defines the tree-relationship between the selected nodes and the current
node)
a node-test (identifies a node within an axis)
zero or more predicates (to further refine the selected node-set)
axisname::nodetest[predicate]
Examples
Example Result
child::book Selects all book nodes that are children of the current
node
ancestor-or-self::book Selects all book ancestors of the current node - and the
current as well if it is a book node
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
XPath Operators
« Previous Next Chapter »
XPath Operators
Below is a list of the operators that can be used in XPath expressions:
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
XPath Examples
« Previous Next Chapter »
Let's try to learn some basic XPath syntax by looking at some examples.
"books.xml":
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Selecting Nodes
Unfortunately, there are different ways of dealing with XPath in Internet Explorer and
other browsers.
In our examples we have included code that should work with most major browsers.
Internet Explorer uses the selectNodes() method to select nodes from the XML
document:
xmlDoc.selectNodes(xpath);
Firefox, Chrome, Opera and Safari use the evaluate() method to select nodes from the
XML document:
Example
/bookstore/book/title
Try it yourself »
Example
/bookstore/book[1]/title
Try it yourself »
There is a problem with this. The example above shows different results in IE and other
browsers.
IE5 and later has implemented that [0] should be the first node, but according to the
W3C standard it should have been [1]!!
A Workaround!
To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage to XPath.
The following example selects the title of the first book node under the bookstore
element:
Example
xml.setProperty("SelectionLanguage","XPath");
xml.selectNodes("/bookstore/book[1]/title");
Try it yourself »
Example
/bookstore/book/price/text()
Try it yourself »
Select price nodes with price>35
The following example selects all the price nodes with a price higher than 35:
Example
/bookstore/book[price>35]/price
Try it yourself »
Example
/bookstore/book[price>35]/title
Try it yourself »
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
You Have Learned XPath, Now What?
« Previous Next Chapter »
XPath Summary
This tutorial has taught you how to find information in an XML document.
You have learned how to use XPath to navigate through elements and attributes in an
XML document.
You have also learned how to use some of the standard functions that are built-in in
XPath.
XSLT
With XSLT you can transform XML documents into other formats, like XHTML.
If you want to learn more about XSLT, please visit our XSLT tutorial.
XQuery
XQuery is designed to query anything that can appear as XML, including databases.
If you want to learn more about XQuery, please visit our XQuery tutorial.
If you want to learn more about XLink and XPointer, please visit our XLink and
XPointer tutorial.
XPath HOME
XPath Intro
XPath Nodes
XPath Syntax
XPath Axes
XPath Operators
XPath Examples
XPath Summary
XPath Reference
XPath Functions
The following reference library defines the functions required for XPath 2.0, XQuery
1.0 and XSLT 2.0.
Functions Reference
AnyURI Node
Accessor Boolean Sequence
Error and Trace Duration/Date/Time Context
Numeric QName
String
fn:error() Example:
fn:error(error) error(fn:QName('http://example.com/test',
fn:error(error,description) 'err:toohigh'), 'Error: Price is too high')
fn:error(error,description,error-object)
Result: Returns
http://example.com/test#toohigh and the string
"Error: Price is too high" to the external
processing environment
fn:trace(value,label) Used to debug queries
Example: number('100')
Result: 100
fn:abs(num) Returns the absolute value of the argument
Example: abs(3.14)
Result: 3.14
Example: abs(-3.14)
Result: 3.14
fn:ceiling(num) Returns the smallest integer that is greater than the
number argument
Example: ceiling(3.14)
Result: 4
fn:floor(num) Returns the largest integer that is not greater than
the number argument
Example: floor(3.14)
Result: 3
fn:round(num) Rounds the number argument to the nearest
integer
Example: round(3.14)
Result: 3
fn:round-half-to-even() Example: round-half-to-even(0.5)
Result: 0
Example: round-half-to-even(1.5)
Result: 2
Example: round-half-to-even(2.5)
Result: 2
Functions on Strings
Name Description
Example: string(314)
Result: "314"
fn:codepoints-to-string(int,int,...) Returns a string from a sequence of code points
Example: string-to-codepoints("Thérèse")
Result: 84, 104, 233, 114, 232, 115, 101
fn:codepoint-equal(comp1,comp2) Returns true if the value of comp1 is equal to the
value of comp2, according to the Unicode code
point collation
(http://www.w3.org/2005/02/xpath-
functions/collation/codepoint), otherwise it returns
false
Example:string-join((), 'sep')
Result: ''
fn:substring(string,start,len) Returns the substring from the start position to the
fn:substring(string,start) specified length. Index of the first character is 1. If
length is omitted it returns the substring from the
start position to the end
Example: substring('Beatles',1,4)
Result: 'Beat'
Example: substring('Beatles',2)
Result: 'eatles'
fn:string-length(string) Returns the length of the specified string. If there is
fn:string-length() no string argument it returns the length of the
string value of the current node
Example: string-length('Beatles')
Result: 7
fn:normalize-space(string) Removes leading and trailing spaces from the
fn:normalize-space() specified string, and replaces all internal sequences
of white space with one and returns the result. If
there is no string argument it does the same on the
current node
Example: translate('12:30','30','45')
Result: '12:45'
Example: translate('12:30','03','54')
Result: '12:45'
Example: translate('12:30','0123','abcd')
Result: 'bc:da'
fn:escape-uri(stringURI,esc-res) Example: escape-
uri("http://example.com/test#car", true())
Result: "https%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fexample.com%2Ftest#car"
Example: escape-
uri("http://example.com/test#car", false())
Result: "http://example.com/test#car"
Example: escape-uri
("http://example.com/~bébé", false())
Result: "http://example.com/~b%C3%A9b
%C3%A9"
fn:contains(string1,string2) Returns true if string1 contains string2, otherwise it
returns false
Example: contains('XML','XM')
Result: true
fn:starts-with(string1,string2) Returns true if string1 starts with string2, otherwise
it returns false
Example: starts-with('XML','X')
Result: true
fn:ends-with(string1,string2) Returns true if string1 ends with string2, otherwise
it returns false
Example: ends-with('XML','X')
Result: false
fn:substring-before(string1,string2) Returns the start of string1 before string2 occurs in
it
Example: substring-before('12/10','/')
Result: '12'
fn:substring-after(string1,string2) Returns the remainder of string1 after string2
occurs in it
Example: substring-after('12/10','/')
Result: '10'
fn:matches(string,pattern) Returns true if the string argument matches the
pattern, otherwise, it returns false
Example: month-from-
dateTime(xs:dateTime("2005-01-10T12:30-
04:10"))
Result: 01
fn:day-from-dateTime(datetime) Returns an integer that represents the day
component in the localized value of the argument
Example: day-from-
Functions Related to QNames
Name Description
fn:QName()
fn:local-name-from-QName()
fn:namespace-uri-from-QName()
fn:namespace-uri-for-prefix()
fn:in-scope-prefixes()
fn:resolve-QName()
Functions on Nodes
Name Description
Functions on Sequences
Name Description
Name Description
Aggregate Functions
Name Description
Example: avg((1,2,3))
Result: 2
fn:max((arg,arg,...)) Returns the argument that is greater than the
others
Example: max((1,2,3))
Result: 3
Example: min((1,2,3))
Result: 1
Name Description
fn:doc(URI)
fn:collection()
fn:collection(string)
Context Functions
Name Description
Example: //book[position()<=3]
Result: Selects the first three book elements
fn:last() Returns the number of items in the processed node
list
Example: //book[last()]
Result: Selects the last book element
fn:current-dateTime() Returns the current dateTime (with timezone)