If double slash (//) is used 2 times in XPath, what does it mean?

前端 未结 3 1276
抹茶落季
抹茶落季 2020-12-08 07:10

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\']
相关标签:
3条回答
  • 2020-12-08 07:42

    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']
    
    • The first time // appears, it selects all div elements in the document with an id attribute value equal to 'add'.
    • The second time // appears, it selects all span elements that are descendents of each of the div elements selected previously.
    • Note that using two double slashes twice is different than just using double slash once. For example, //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'.
    0 讨论(0)
  • 2020-12-08 07:42

    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.

    0 讨论(0)
  • 2020-12-08 07:43

    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.

    0 讨论(0)
提交回复
热议问题