W3schools Xpath PDF
W3schools Xpath PDF
W3schools Xpath PDF
XPath is a major element in W3C's XSLT standard - and XQuery and XPointer are
both built on XPath expressions.
XPath Reference
At W3Schools you will find a complete reference of all the built-in functions in XPath 2.0,
XQuery 1.0 and XSLT 2.0.
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.
1. XPath Introduction
HTML / XHTML
XML / XML Namespaces
If you want to study these subjects first, find the tutorials on our Home page.
What is XPath?
XPath is a syntax for defining parts of an XML document
XPath uses path expressions to navigate in XML
documents
XPath contains a library of standard functions
XPath is a major element in XSLT
XPath is a W3C recommendation
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.
2. XPath Nodes
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
Atomic values are nodes with no children or parent.
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>
3. XPath Syntax
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
Selects nodes in the document from the current node that match
//
the selection no matter where they are
@ 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.
In the table below we have listed some path expressions with predicates and the result of
the expressions:
/bookstore/book[1]
Note: In IE 5,6,7,8,9 first node is[0], but according
to W3C, it is [1]. To solve this problem in IE, set the
SelectionLanguage to XPath:
In JavaScript:
xml.setProperty("SelectionLanguage","XPath");
Wildcard Description
In the table below we have listed some path expressions and the result of the
expressions:
In the table below we have listed some path expressions and the result of the
expressions:
< 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)
Examples
Example Result
XPath Operators
Below is a list of the operators that can be used in XPath expressions:
+ Addition 6+4
- Subtraction 6-4
* Multiplication 6*4
= Equal price=9.80
or or price=9.80 or price=9.70
< bookstore>
< /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
Select the title of the first book
The following example selects the title of the first book node under the bookstore
element:
Example
/bookstore/book[1]/title
Example
/bookstore/book/price[text()]
Example
/bookstore/book[price>35]/price
Example
/bookstore/book[price>35]/title
7. You Have Learned XPath, Now What?
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.
8. XPath, XQuery, and XSLT Functions
The following reference library defines the functions required for XPath 2.0, XQuery
1.0 and XSLT 2.0.
Functions Reference
Accessor AnyURI
Node
Error and Trace Boolean
Sequence
Numeric Duration/Date/Time
Context
String QName
Accessor Functions
Name Description
fn:error()
Example:
fn:error(error)
error(fn:QName('http://example.com/test',
fn:error(error,description)
fn:error(error,description,error-object) 'err:toohigh'), 'Error: Price is too high')
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: abs(3.14)
fn:abs(num) Result: 3.14
Example: abs(-3.14)
Result: 3.14
Returns the smallest integer that is greater than
the number argument
fn:ceiling(num)
Example: ceiling(3.14)
Result: 4
Returns the largest integer that is not greater
than the number argument
fn:floor(num)
Example: floor(3.14)
Result: 3
Rounds the number argument to the nearest
integer
fn:round(num)
Example: round(3.14)
Result: 3
Example: round-half-to-even(0.5)
Result: 0
fn:round-half-to-even()
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"
Returns a string from a sequence of code points
Example:string-join((), 'sep')
Result: ''
Returns the substring from the start position to
the specified length. Index of the first character
is 1. If length is omitted it returns the substring
from the start position to the end
fn:substring(string,start,len)
fn:substring(string,start) Example: substring('Beatles',1,4)
Result: 'Beat'
Example: substring('Beatles',2)
Result: 'eatles'
Returns the length of the specified string. If
there is no string argument it returns the length
fn:string-length(string)
of the string value of the current node
fn:string-length()
Example: string-length('Beatles')
Result: 7
Removes leading and trailing spaces from the
specified string, and replaces all internal
sequences of white space with one and returns
fn:normalize-space(string)
the result. If there is no string argument it does
fn:normalize-space()
the same on the current node
Example: translate('12:30','03','54')
Result: '12:45'
Example: translate('12:30','0123','abcd')
Result: 'bc:da'
Example: escape-
uri("http://example.com/test#car", true())
Result:
"http%3A%2F%2Fexample.com%2Ftest#car"
Example: escape-
fn:escape-uri(stringURI,esc-res)
uri("http://example.com/test#car", false())
Result: "http://example.com/test#car"
Example: escape-uri
("http://example.com/~bb", false())
Result:
"http://example.com/~b%C3%A9b%C3%A9"
Returns true if string1 contains string2,
otherwise it returns false
fn:contains(string1,string2)
Example: contains('XML','XM')
Result: true
Returns true if string1 starts with string2,
otherwise it returns false
fn:starts-with(string1,string2)
Example: starts-with('XML','X')
Result: true
Returns true if string1 ends with string2,
otherwise it returns false
fn:ends-with(string1,string2)
Example: ends-with('XML','X')
Result: false
Returns the start of string1 before string2 occurs
in it
fn:substring-before(string1,string2)
Example: substring-before('12/10','/')
Result: '12'
Returns the remainder of string1 after string2
fn:substring-after(string1,string2)
occurs in it
Example: substring-after('12/10','/')
Result: '10'
Returns true if the string argument matches the
pattern, otherwise, it returns false
fn:matches(string,pattern)
Example: matches("Merano", "ran")
Result: true
Returns a string that is created by replacing the
given pattern with the replace argument
fn:resolve-uri(relative,base)
Example: not(true())
Result: false
Returns the boolean value true
fn:true()
Example: true()
Result: true
Returns the boolean value false
fn:false()
Example: false()
Result: false
Functions on Durations, Dates and Times
Name Description
Example: month-from-
dateTime(xs:dateTime("2005-01-10T12:30-
04:10"))
Result: 01
Returns an integer that represents the day
component in the localized value of the
argument
fn:day-from-dateTime(datetime)
Example: day-from-
dateTime(xs:dateTime("2005-01-10T12:30-
04:10"))
Result: 10
Returns an integer that represents the hours
component in the localized value of the
argument
fn:hours-from-dateTime(datetime)
Example: hours-from-
dateTime(xs:dateTime("2005-01-10T12:30-
04:10"))
Result: 12
Returns an integer that represents the minutes
component in the localized value of the
argument
fn:minutes-from-dateTime(datetime)
Example: minutes-from-
dateTime(xs:dateTime("2005-01-10T12:30-
04:10"))
Result: 30
Returns a decimal that represents the seconds
component in the localized value of the
argument
fn:seconds-from-dateTime(datetime)
Example: seconds-from-
dateTime(xs:dateTime("2005-01-10T12:30:00-
04:10"))
Result: 0
Returns the time zone component of the
fn:timezone-from-dateTime(datetime)
argument if any
Example: hours-from-time(xs:time("10:22:00"))
Result: 10
Returns an integer that represents the minutes
component in the localized value of the
argument
fn:minutes-from-time(time)
Example: minutes-from-
time(xs:time("10:22:00"))
Result: 22
Returns an integer that represents the seconds
component in the localized value of the
argument
fn:seconds-from-time(time)
Example: seconds-from-
time(xs:time("10:22:00"))
Result: 0
Returns the time zone component of the
fn:timezone-from-time(time)
argument if any
fn:adjust-date-to-
If the timezone argument is empty, it returns a
timezone(date,timezone)
date without a timezone. Otherwise, it returns a
date with a timezone
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
Name Description
Example: reverse(("ab"))
Result: ("ab")
Returns a sequence of items from the position
specified by the start argument and continuing
for the number of items specified by the len
argument. The first item is located at position 1
Name Description
Returns the argument if it contains zero or one
fn:zero-or-one(item,item,...)
items, otherwise it raises an error
Name Description
Aggregate Functions
Name Description
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
Returns the number of items in the processed
node list
fn:last()
Example: //book[last()]
Result: Selects the last book element
fn:current-dateTime() Returns the current dateTime (with timezone)