What does a double-slash used twice in an XPath selector mean?
Suppose I\'m using a path like:
//div[@id=\'add\']//span[@id=addone\']
Double slash (//
) is the descendant-or-self axis; it is short for /descendant-or-self::node()/
.
In your example XPath:
//div[@id='add']//span[@id='addone']
//
appears, it selects all div
elements in the
document with an id
attribute value equal to 'add'
.//
appears, it selects all span
elements that are
descendents of each of the div
elements selected previously.//span[@id='addone']
would select
all span
elements with @id='addone'
in the entire document, regardless of whether they are a descendent of a div
with @id='add'
.If you'd have this:
<div id='add'>
<ul>
<li>
<span id='add one' />
</li>
</ul>
</div>
Then
//div[@id='add']//span[@id='addone']
will result in the span
because the second //
means you look for any child relative to
div[@id='add']
that is span[@id='add one']
.
If you'd use one slash
//div[@id='add']/span[@id='addone']
then of course you won't find it because then you look for a direct child and you'd have to use
//div[@id='add']/ul/li/span[@id='addone']
So the second //
is very useful in avoiding extra hierarchy in your XPaths.
A double slash "//
" means any descendant node of the current node in the HTML tree which matches the locator.
A single slash "/
" means a node which is a direct child of the current.
//div[@id='add']//span[@id=addone']
will match:
<div id="add">
<div>
<span id="addone">
</div>
</div>
And:
<div id="add">
<span id="addone">
</div>
//div[@id='add']/span[@id=addone']
will match only the second HTML tree.