Xpath
Xpath
#xpath
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Select text 2
Select an element 3
Syntax 5
Remarks 5
Examples 5
Syntax 7
Remarks 7
Examples 7
Check if Deborah has a master and its text value is not empty 7
Check if Dobby has a master and its text value is not empty 7
Syntax 9
Parameters 9
Remarks 9
Examples 9
Examples 13
Examples 14
Syntax 16
Parameters 16
Remarks 17
Examples 17
Find My ancestors 17
Find My Parent 17
Find my brother 18
Syntax 23
Parameters 23
Remarks 23
Examples 23
Remarks 25
Examples 25
Traversing ancestors 26
Remarks 28
Examples 28
Examples 29
Chapter 12: Select nodes with names equal to or containing some string 31
Syntax 31
Parameters 31
Remarks 31
Examples 31
Search for nodes that has name that starts with Star 32
Search for nodes that has name that ends with Ball 33
Credits 36
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: xpath
It is an unofficial and free xpath ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official xpath.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with xpath
Remarks
XPath is a language for addressing parts of an XML document.
It is used in XSLT and is a subset of XQuery. Libraries are available for most other programming
languages as well.
Versions
1.0 1999-12-16
2.0 2007-01-23
3.0 2014-04-08
Examples
Sample XML (without namespaces)
Here is some sample XML against which example XPaths can be written:
<r>
<e a="1"/>
<f a="2" b="1">Text 1</f>
<f/>
<g>
<i c="2">Text 2</i>
Text 3
<j>Text 4</j>
</g>
</r>
Select text
https://riptutorial.com/ 2
For the sample XML (without namespaces):
This XPath,
/r/f/text()
"Text 1"
string(/r/f)
"Text 1"
Select an element
This XPath,
/r/e
<e a="1"/>
<html>
<body>
<a>link</a>
<div class='container' id='divone'>
<p class='common' id='enclosedone'>Element One</p>
<p class='common' id='enclosedtwo'>Element Two</p>
</div>
</body>
</html>
https://riptutorial.com/ 3
Find an element with a specific id in a particular path
A quick way to test your xpath is in your browser developer tool console.
Format is
$ - specifies it is a selector.
Example:
$x("//button[text() ='Submit']")
When this command is entered it will return all occurrences of elements that are buttons with text
equal to Submit.
https://riptutorial.com/ 4
Chapter 2: Check if a node is present
Syntax
• boolean(path_to_node)
Remarks
Boolean function has other uses
Examples
Does the animal have tusks?
XML
<Animal>
<legs>4</legs>
<eyes>2</eyes>
<horns>2</horns>
<tail>1</tail>
</Animal>
XPATH
boolean(/Animal/tusks)
OUTPUT
false
XPATH
<Animal>
<legs>4</legs>
<eyes>2</eyes>
<horns>2</horns>
<tail>1</tail>
</Animal>
XPATH
https://riptutorial.com/ 5
boolean(/Animal/horns)
OUTPUT
true
XML
<House>
<LivingRoom>
<plant name="rose"/>
</LivingRoom>
<TerraceGarden>
<plant name="passion fruit"/>
<plant name="lily"/>
<plant name="golden duranta"/>
</TerraceGarden>
</House>
XPATH
boolean(/House//plant)
OUTPUT
true
https://riptutorial.com/ 6
Chapter 3: Check if a node's text is empty
Syntax
• boolean(path_to_node/text())
• string(path_to_node) != ''
Remarks
Boolean function has other uses
Examples
Check if Deborah has a master and its text value is not empty
XML
<Deborah>
<address>Dark world</address>
<master>Babadi</master>
<ID>#0</ID>
<colour>red</colour>
<side>evil</side>
</Deborah>
XPATH
boolean(/Deborah/master/text())
OR
string(/Deborah/master) != ''
OUTPUT
true
Check if Dobby has a master and its text value is not empty
XML
https://riptutorial.com/ 7
<Dobby>
<address>Hogwartz</address>
<master></master>
<colour>wheatish</colour>
<side>all good</side>
</Dobby>
XPATH
boolean(/Dobby/master/text())
OR
string(/Dobby/master) != ''
OUTPUT
false
https://riptutorial.com/ 8
Chapter 4: Find nodes that have a specific
attribute
Syntax
1. Inside a specific node
• /path to/element[@attribute_name]
2. Anywhere in the document
• //*[@attribute_name]
3. Inside a specific node with some value
• /path to/element[@attribute_name='search value']
• /path to/element[@attribute_name="search value"]
4. Anywhere in the document with some value
• //*[@attribute_name='search string']
• //*[@attribute_name="search string"]
Parameters
Selector function
Remarks
Using [@attribute_name] we can select nodes that have the attribute irrespective of the value.
We can use any of the functions or combination of the functions such as starts-with and
lowercase, for example, with this selector to suit our needs.
Examples
Find nodes with a specific attribute
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
https://riptutorial.com/ 9
/Galaxy/*[@name]
or
//*[@name]
OUTPUT
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[@name='Sun']
or
//*[@name='Sun']
OUTPUT
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[contains(@name,'Ear')]
or
https://riptutorial.com/ 10
//*[contains(@name,'Ear')]
/Galaxy/*[contains(@name, "Ear")]
OUTPUT
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[contains(lower-case(@name),'ear')]
or
//*[contains(lower-case(@name),'ear')]
//*[contains(lower-case(@name), "ear")]
OUTPUT
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
https://riptutorial.com/ 11
/Galaxy/*[starts-with(lower-case(@name),'ear')]
or
//*[starts-with(lower-case(@name),'ear')]
OUTPUT
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[ends-with(lower-case(@type),'tar')]
or
//*[ends-with(lower-case(@type),'tar')]
OUTPUT
https://riptutorial.com/ 12
Chapter 5: Finding elements containing
specific attributes
Examples
Find all elements with a certain attribute
<root>
<element foobar="hello_world" />
<element example="this is one!" />
</root>
/root/element[@foobar]
<root>
<element foobar="hello_world" />
<element example="this is one!" />
</root>
/root/element[@foobar = 'hello_world']
/root/element[@foobar="hello_world"]
https://riptutorial.com/ 13
Chapter 6: Finding elements containing
specific text
Examples
Find all elements with certain text
<root>
<element>hello</element>
<another>
hello
</another>
<example>Hello, <nested> I am an example </nested>.</example>
</root>
//*[text() = 'hello']
will return the <element>hello</element> element, but not the <another> element. This is because the
<another> element contains whitespace surrounding the hello text.
//*[normalize-space(text()) = 'hello']
or
//*[normalize-space() = 'hello']
which will trim the surrounding whitespace before doing the comparison. Here we can see that the
text() node specifier is optional when using normalize-space.
To find an element containing specific text, you can use the contains function. The following
expression will return the <example> element:
//example[contains(text(), 'Hello')]
If you want to find text that spans multiple children/text nodes, then you can use . instead of text()
. . refers to the entire text content of the element and it's children.
https://riptutorial.com/ 14
To see the multiple text nodes, you can use:
//example//text()
• "Hello, "
• " I am an example "
• "."
And to more clearly see the entire text content of an element, one can use the string function:
string(//example[1])
or just
string(//example)
Hello, I am an example .
The latter works because, if a node-set is passed into functions like string, XPath 1.0 just looks at
the first node (in document order) in that node-set, and ignores the rest.
so:
string(/root/*)
would return:
hello
https://riptutorial.com/ 15
Chapter 7: Get nodes relative to the current
node
Syntax
1. All ancestors of a node
• /path to the node/ancestor::node()
2. A specific ancestor of a node
• /path to the node/ancestor::ancestor_name
3. Parent of a node
• /path to the node/parent::node()
4. Following siblings of a node
• /path to the node/following-sibling::node()
5. A specific sibling following a node
• /path to the node/following-sibling::sibling_name
6. Preceding siblings of a node
• /path to the node/preceding-sibling::node()
7. A specific sibling preceding a node
• /path to the node/preceding-sibling::sibling_name
8. All immediate child nodes of a node
• /path to the node/child::node()
9. A specific immediate child node of a node
• /path to the node/child::chid_name
10. All the descendants of a node
• /path to the node/descendant::node()
11. All specific descendants of a node
• /path the to node/descendant::descendant_name
Parameters
Axis selects
https://riptutorial.com/ 16
Remarks
These axes can be used in combination with other functions to suit our needs.
Examples
Find My ancestors
XML
XPATH
//Me/ancestor::node()
OUTPUT
Find My Parent
XML
XPATH
//Me/ancestor::Dad
or
https://riptutorial.com/ 17
//Me/parent::node()
OUTPUT
XML
XPATH
//Me/ancestor::GrandFather
or
//Me/parent::node()/parent::node()
OUTPUT
Find my brother
XML
XPATH
https://riptutorial.com/ 18
//Me/following-sibling::brother
OUTPUT
XML
<Dashavatar>
<Avatar name="Matsya"/>
<Avatar name="Kurma"/>
<Avatar name="Varaha"/>
<Avatar name="Narasimha"/>
<Avatar name="Vamana"/>
<Avatar name="Balabhadra"/>
<Avatar name="Parashurama"/>
<Avatar name="Rama"/>
<Avatar name="Krishna"/>
<Avatar name="Kalki"/>
</Dashavatar>
XPATH
//Avatar[@name='Parashurama']/preceding-sibling::node()
OUTPUT
<Avatar name="Matsya"/>
<Avatar name="Kurma"/>
<Avatar name="Varaha"/>
<Avatar name="Narasimha"/>
<Avatar name="Vamana"/>
<Avatar name="Balabhadra"/>
XML
<Dashavatar>
<Avatar name="Matsya"/>
<Avatar name="Kurma"/>
<Avatar name="Varaha"/>
<Avatar name="Narasimha"/>
<Avatar name="Vamana"/>
<Avatar name="Balabhadra"/>
<Avatar name="Parashurama"/>
<Avatar name="Rama"/>
<Avatar name="Krishna"/>
<Avatar name="Kalki"/>
</Dashavatar>
https://riptutorial.com/ 19
XPATH
//Avatar[@name='Parashurama']/following-sibling::node()
OUTPUT
XML
<Dashavatar>
<Avatar name="Matsya"/>
<Avatar name="Kurma"/>
<Avatar name="Varaha"/>
<Avatar name="Narasimha"/>
<Avatar name="Vamana"/>
<Avatar name="Balabhadra"/>
<Avatar name="Parashurama"/>
<Avatar name="Rama"/>
<Avatar name="Krishna"/>
<Avatar name="Kalki"/>
</Dashavatar>
XPATH
//Avatar[@name='Parashurama']/following-sibling::Avatar |
//Avatar[@name='Parashurama']/preceding-sibling::Avatar
OUTPUT
XML
<House>
<Rooms>10</Rooms>
<People>4</People>
<TVs>4</TVs>
https://riptutorial.com/ 20
<Floors>2</Floors>
</House>
XPATH
/House/child::node()
OUTPUT
<Rooms>10</Rooms>
<People>4</People>
<TVs>4</TVs>
<Floors>2</Floors>
XML
<House>
<numRooms>4</numRooms>
<Room name="living"/>
<Room name="master bedroom"/>
<Room name="kids' bedroom"/>
<Room name="kitchen"/>
</House>
XPATH
/House/child::Room
or
/House/*[local-name()='Room']
OUTPUT
XML
<House>
<numRooms>4</numRooms>
<Floor number="1">
<Room name="living"/>
<Room name="kitchen"/>
https://riptutorial.com/ 21
</Floor>
<Floor number="2">
<Room name="master bedroom"/>
<Room name="kids' bedroom"/>
</Floor>
</House>
XPATH
/House/descendant::Room
OUTPUT
https://riptutorial.com/ 22
Chapter 8: Get the count of nodes
Syntax
• count(node-set)
Parameters
function returns
Remarks
We can use this in combination of other functions and axes to suit our needs.
Examples
How many children does Goku have?
XML
<Goku>
<child name="Gohan"/>
<child name="Goten"/>
</Goku>
XPATH
count(/Goku/child)
OUTPUT
2.0
XML
<House>
<LivingRoom>
<plant name="rose"/>
</LivingRoom>
<TerraceGarden>
https://riptutorial.com/ 23
<plant name="passion fruit"/>
<plant name="lily"/>
<plant name="golden duranta"/>
</TerraceGarden>
</House>
XPATH
count(/House//plant)
OUTPUT
4.0
https://riptutorial.com/ 24
Chapter 9: Location paths and axes
Remarks
An XPath location path is a series of location steps separated by a / character:
step1/step2/step3
A location step contains an axis, a node test, and an optional list of predicates. The axis and the
node test are separated by two colon characters ::. The predicates are enclosed in square
brackets:
axis::nodeTest[predicate1][predicate2]
The evaluation of a location path starts with a node set containing the context node given by the
context of the expression, or the root node, if the location path starts with a /. At each step, each
node N in the original node set is replaced with the set of nodes that
The result of a location path expression is the final node set obtained after processing all location
steps.
Examples
Traversing child elements
Traversing from the root node to a descendant element using the child axis:
/child::html/child::body/child::div/child::span
Since the child axis is the default axis, this can be abbreviated to:
/html/body/div/span
The descendant and descendant-or-self axes can be used to find all descendant elements of a node
at any depth. In contrast, the child axis only traverses immediate children.
/child::html/descendant::span
/child::html/descendant-or-self::*
https://riptutorial.com/ 25
The double slash // is a shortcut for /descendant-or-self::node()/. So the following expressions
are equivalent:
table//td
child::table/descendant-or-self::node()/child::td
child::table/descendant::td
table/descendant::td
Traversing ancestors
The parent axis contains only the parent of a node. The following expression selects the html
element by taking a detour over the body element:
/child::html/child::body/parent::html
The ancestor and ancestor-or-self axes traverse all ancestors of a node. The following expression
returns all div elements that are ancestors of the context node:
ancestor::div
The self axis only contains the context node itself. The expression . is a shortcut for self::node()
and always matches the context node. The . shortcut is useful for enumerating descendants of the
context node. The following expressions are equivalent:
.//span
self::node()/descendant-or-self::node()/child::span
descendant::span
The self axis can be helpful in XPath 1.0 predicates. For example, to select all h1, h2, and h3
children of the context node:
The following-sibling and preceding-sibling axes contain the siblings before or after the context
node, and the following and preceding axes contain all nodes in the document before or after the
context node, but:
Examples:
https://riptutorial.com/ 26
following::span[1]
following-sibling::*[last()]
The attribute and namespace axes contain all attribute and namespace nodes of an element. The
shortcut @ stands for attribute::, so the following are equivalent:
child::div/attribute::class
div/@class
https://riptutorial.com/ 27
Chapter 10: Namespaces
Remarks
XPath 1.0 doesn't have the concept of a default namespace.
Also, the namespace prefixes defined in the original XML document do not affect XPath -
namespace prefixes have to be explicitly registered with the XPath provider, otherwise prefixes
can't be used at all in the XPath expression.
Examples
Namespace aware functions
<root xmlns="http://test/">
<element xmlns:example="http://foobar/">
<example:hello_world attribute="another example" />
</element>
</root>
The expression /root will return nothing, because there is no non-namespaced element called root
at the root level of the document. However, The following will return the <root
xmlns="http://test/"> element.
https://riptutorial.com/ 28
Chapter 11: Select nodes based on their
children
Examples
Select nodes based on child count
Sample XML
<Students>
<Student>
<Name>
<First>Ashley</First>
<Last>Smith</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
<Exam2>B</Exam2>
<Final>A</Final>
</Grades>
</Student>
<Student>
<Name>
<First>Bill</First>
<Last>Edwards</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
</Grades>
</Student>
</Students>
XPath
//Student[count(./Grades/*) > 1]
Output
<Student>
<Name>
<First>Ashley</First>
<Last>Smith</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
<Exam2>B</Exam2>
<Final>A</Final>
</Grades>
</Student>
https://riptutorial.com/ 29
Select nodes based on specific child node
Sample XML
<Students>
<Student>
<Name>
<First>Ashley</First>
<Last>Smith</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
<Exam2>B</Exam2>
<Final>A</Final>
</Grades>
</Student>
<Student>
<Name>
<First>Bill</First>
<Last>Edwards</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
</Grades>
</Student>
</Students>
XPath
//Student[./Grades/Exam2]
or
//Student[.//Exam2]
Output
<Student>
<Name>
<First>Ashley</First>
<Last>Smith</Last>
</Name>
<Grades>
<Exam1>A</Exam1>
<Exam2>B</Exam2>
<Final>A</Final>
</Grades>
</Student>
https://riptutorial.com/ 30
Chapter 12: Select nodes with names equal to
or containing some string
Syntax
1. Inside a specific node:
{path-to-parent}/name()='search string']
//*[name()='search string']
Parameters
Remarks
local-name() result does not include prefix (lookup name() XPATH function for it)
Examples
Search for nodes with name as Light, Device or Sensor
XML
<Galaxy>
<Light>sun</Light>
<Device>satellite</Device>
<Sensor>human</Sensor>
<Name>Milky Way</Name>
</Galaxy>
XPATH
or
https://riptutorial.com/ 31
OUTPUT
<Light>sun</Light>
<Device>satellite</Device>
<Sensor>human</Sensor>
XML
<Data>
<BioLight>
<name>Firefly</name>
<model>Insect</model>
</BioLight>
<ArtificialLight>
<name>Fire</name>
<model>Natural element</model>
<source>flint</source>
</ArtificialLight>
<SolarLight>
<name>Sun</name>
<model>Star</model>
<source>helium</source>
</SolarLight>
</Data>
XPATH
/Data/*[contains(local-name(),"Light")]
or
//*[contains(local-name(),"Light")]
OUTPUT
<BioLight>
<name>Firefly</name>
<model>Insect</model>
</BioLight>
<ArtificialLight>
<name>Fire</name>
<model>Natural element</model>
<source>flint</source>
</ArtificialLight>
<SolarLight>
<name>Sun</name>
<model>Star</model>
<source>helium</source>
</SolarLight>
Search for nodes that has name that starts with Star
https://riptutorial.com/ 32
XML
<College>
<FootBall>
<Members>20</Members>
<Coach>Archie Theron</Coach>
<Name>Wild cats</Name>
<StarFootballer>David Perry</StarFootballer>
</FootBall>
<Academics>
<Members>100</Members>
<Teacher>Tim Jose</Teacher>
<Class>VII</Class>
<StarPerformer>Lindsay Rowen</StarPerformer>
</Academics>
</College>
XPATH
/College/*/*[starts-with(local-name(),"Star")]
or
//*[starts-with(local-name(),"Star")]
OUTPUT
<StarFootballer>David Perry</StarFootballer>
<StarPerformer>Lindsay Rowen</StarPerformer>
Search for nodes that has name that ends with Ball
XML
<College>
<FootBall>
<Members>20</Members>
<Coach>Archie Theron</Coach>
<Name>Wild cats</Name>
<StarPlayer>David Perry</StarPlayer>
</FootBall>
<VolleyBall>
<Members>24</Members>
<Coach>Tim Jose</Coach>
<Name>Avengers</Name>
<StarPlayer>Lindsay Rowen</StarPlayer>
</VolleyBall>
<FoosBall>
<Members>22</Members>
<Coach>Rahul Mehra</Coach>
<Name>Playerz</Name>
<StarPlayer>Amanda Ren</StarPlayer>
</FoosBall>
</College>
https://riptutorial.com/ 33
XPATH
/College/*[ends-with(local-name(),"Ball")]
or
//*[ends-with(local-name(),"Ball")]
OUTPUT
<FootBall>
<Members>20</Members>
<Coach>Archie Theron</Coach>
<Name>Wild cats</Name>
<StarPlayer>David Perry</StarPlayer>
</FootBall>
<VolleyBall>
<Members>24</Members>
<Coach>Tim Jose</Coach>
<Name>Avengers</Name>
<StarPlayer>Lindsay Rowen</StarPlayer>
</VolleyBall>
<FoosBall>
<Members>22</Members>
<Coach>Rahul Mehra</Coach>
<Name>Playerz</Name>
<StarPlayer>Amanda Ren</StarPlayer>
</FoosBall>
XML
<Galaxy>
<Light>sun</Light>
<Device>satellite</Device>
<Sensor>human</Sensor>
<Name>Milky Way</Name>
</Galaxy>
XPATH
/Galaxy/*[lower-case(local-name())="light"]
or
//*[lower-case(local-name())="light"]
OUTPUT
<Light>sun</Light>
https://riptutorial.com/ 34
Read Select nodes with names equal to or containing some string online:
https://riptutorial.com/xpath/topic/3095/select-nodes-with-names-equal-to-or-containing-some-
string
https://riptutorial.com/ 35
Credits
S.
Chapters Contributors
No
Check if a node is
2 suchitra nair
present
Check if a node's
3 suchitra nair
text is empty
Finding elements
5 containing specific Keith Hall
attributes
Finding elements
6 containing specific Keith Hall
text
https://riptutorial.com/ 36