Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
HTML
XML
If you want to study these subjects first, find the tutorials on our Home page.
What is XPath?
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.
Look at the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Example of nodes in the XML document above:
<bookstore> (root element node)
<author>J K. Rowling</author> (element node)
lang="en" (attribute node)
Atomic values
Atomic values are nodes with no children or parent.
Example of atomic values:
J K. Rowling
"en"
Items
Items are atomic values or nodes.
Relationship of Nodes
Parent
Each element and attribute has one 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
Element nodes may have zero, one or more 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
Nodes that have the same parent.
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
A node's parent, parent's parent, etc.
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
A node's children, children's children, etc.
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 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.
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 attributes
In the table below we have listed some path expressions and the result of
the expressions:
Path Expression
Result
bookstore
/bookstore
bookstore/book
//book
bookstore//book
//@lang
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:
Path Expression
Result
/bookstore/book[1]
/bookstore/book[last()]
/bookstore/book[last()-1]
/bookstore/book[position()<3]
//title[@lang]
//title[@lang='en']
/bookstore/book[price>35.00]
/
bookstore/book[price>35.00]/title
Description
@*
node()
In the table below we have listed some path expressions and the result of
the expressions:
Path Expression
Result
/bookstore/*
//*
//title[@*]
Result
//book/title | //book/price
//title | //price
/bookstore/book/title | //price
XPath Axes
The XML Example Document
We will use the following XML document in the examples below.
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
XPath Axes
An axis defines a node-set relative to the current node.
AxisName
Result
ancestor
ancestor-or-self
attribute
child
descendant
descendant-orself
following
following-sibling
namespace
parent
preceding
Selects all nodes that appear before the current node in the
document, except ancestors, attribute nodes and namespace nodes
precedingsibling
self
Examples
Example
Result
child::book
Selects all book nodes that are children of the current node
attribute::lang
child::*
attribute::*
child::text()
child::node()
descendant::book
ancestor::book
ancestor-or-self::book
child::*/child::price
XPath Operators
An XPath expression returns either a node-set, a string, a Boolean, or a
number.
XPath Operators
Below is a list of the operators that can be used in XPath expressions:
Operator
Description
Example
//book | //cd
Addition
6+4
Subtraction
6-4
Multiplication
6*4
div
Division
8 div 4
Equal
price=9.80
!=
Not equal
price!=9.80
<
Less than
price<9.80
<=
price<=9.80
>
Greater than
price>9.80
>=
price>=9.80
or
or
price=9.80 or price=9.70
and
and
mod
5 mod 2
XPath Examples
Let's try to learn some basic XPath syntax by looking at some examples.
<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>
View the "books.xml" file in your browser.
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:
xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);
Example
/bookstore/book/title
Try it yourself
Example
/bookstore/book[1]/title
Try it yourself
Example
/bookstore/book/price[text()]
Try it yourself
Example
/bookstore/book[price>35]/price
Try it yourself
Example
/bookstore/book[price>35]/title
Functions Reference
Accessor
Error and Trace
Numeric
String
AnyURI
Node
Sequence
Context
Boolean
Duration/Date/Time
QName
Accessor Functions
Name
Description
fn:node-name(node)
fn:nilled(node)
fn:data(item.item,...)
fn:base-uri()
fn:base-uri(node)
fn:document-uri(node)
Description
fn:error()
fn:error(error)
fn:error(error,description)
fn:error(error,description,e
Example: error(fn:QName('http://example.com/test',
'err:toohigh'), 'Error: Price is too high')
rror-object)
Description
fn:number(arg)
fn:abs(num)
fn:ceiling(num)
fn:floor(num)
fn:round(num)
Result: 3
fn:round-half-toeven()
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
fn:string(arg)
Example: string(314)
Result: "314"
fn:codepoints-tostring((int,int,...))
Example: string-to-codepoints("Thrse")
Result: (84, 104, 233, 114, 232, 115, 101)
fn:codepointequal(comp1,comp2)
fn:compare(comp1,comp2)
fn:compare(comp1,comp2,c
ollation)
Example: substring('Beatles',1,4)
Result: 'Beat'
Example: substring('Beatles',2)
Result: 'eatles'
fn:string-length(string)
fn:string-length()
Example: string-length('Beatles')
Result: 7
fn:normalize-space(string)
fn:normalize-space()
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,escres)
Example: escape-uri("http://example.com/test#car",
true())
Result: "http%3A%2F%2Fexample.com%2Ftest#car"
returns false
Example: contains('XML','XM')
Result: true
fn:starts-with(string1,string2)
Example: starts-with('XML','X')
Result: true
fn:ends-with(string1,string2)
Example: ends-with('XML','X')
Result: false
fn:substringbefore(string1,string2)
Example: substring-before('12/10','/')
Result: '12'
fn:substringafter(string1,string2)
Example: substring-after('12/10','/')
Result: '10'
fn:matches(string,pattern)
fn:tokenize(string,pattern)
Description
fn:resolve-uri(relative,base)
Description
fn:boolean(arg)
fn:not(arg)
fn:true()
fn:false()
Description
fn:dateTime(date,time)
fn:years-fromduration(datetimedur)
fn:months-fromduration(datetimedur)
fn:days-fromduration(datetimedur)
fn:hours-fromduration(datetimedur)
fn:minutes-fromduration(datetimedur)
fn:seconds-fromduration(datetimedur)
fn:year-fromdateTime(datetime)
Example: year-from-dateTime(xs:dateTime("2005-0110T12:30-04:10"))
Result: 2005
fn:month-fromdateTime(datetime)
Example: month-from-dateTime(xs:dateTime("2005-0110T12:30-04:10"))
Result: 01
fn:day-fromdateTime(datetime)
Example: day-from-dateTime(xs:dateTime("2005-0110T12:30-04:10"))
Result: 10
fn:hours-fromdateTime(datetime)
Example: hours-from-dateTime(xs:dateTime("2005-0110T12:30-04:10"))
Result: 12
fn:minutes-fromdateTime(datetime)
Example: minutes-from-dateTime(xs:dateTime("2005-0110T12:30-04:10"))
Result: 30
fn:seconds-fromdateTime(datetime)
Example: seconds-from-dateTime(xs:dateTime("2005-0110T12:30:00-04:10"))
Result: 0
fn:timezone-fromdateTime(datetime)
fn:year-from-date(date)
Example: year-from-date(xs:date("2005-04-23"))
Result: 2005
fn:month-from-date(date)
Example: month-from-date(xs:date("2005-04-23"))
Result: 4
fn:day-from-date(date)
Example: day-from-date(xs:date("2005-04-23"))
Result: 23
fn:timezone-from-date(date)
fn:hours-from-time(time)
Example: hours-from-time(xs:time("10:22:00"))
Result: 10
fn:minutes-from-time(time)
Example: minutes-from-time(xs:time("10:22:00"))
Result: 22
fn:seconds-from-time(time)
Example: seconds-from-time(xs:time("10:22:00"))
Result: 0
fn:timezone-from-time(time)
fn:adjust-dateTime-to-
timezone(datetime,timezone)
fn:adjust-date-totimezone(date,timezone)
fn:adjust-time-totimezone(time,timezone)
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
fn:name()
fn:name(nodeset)
Returns the name of the current node or the first node in the
specified node set
fn:local-name()
fn:localname(nodeset)
Returns the name of the current node or the first node in the
specified node set - without the namespace prefix
fn:namespace-uri()
fn:namespaceuri(nodeset)
fn:lang(lang)
fn:root()
fn:root(node)
Returns the root of the tree to which the current node or the
specified belongs. This will usually be a document node
Functions on Sequences
General Functions on Sequences
Name
Description
fn:indexof((item,item,...),searchitem)
fn:reverse((item,item,...))
Description
fn:zero-orone(item,item,...)
fn:one-ormore(item,item,...)
fn:exactlyone(item,item,...)
Description
fn:deepequal(param1,param2,collation)
Returns true if param1 and param2 are deepequal to each other, otherwise it returns false
Aggregate Functions
Name
Description
fn:count((item,item,...))
fn:avg((arg,arg,...))
fn:max((arg,arg,...))
fn:min((arg,arg,...))
fn:sum(arg,arg,...)
Description
fn:id((string,string,...),node)
fn:doc(URI)
fn:doc-available(URI)
fn:collection()
fn:collection(string)
Context Functions
Name
Description
fn:position()
fn:last()
fn:current-dateTime()
fn:current-date()
fn:current-time()
fn:implicit-timezone()
fn:default-collation()
fn:static-base-uri()