What's the difference between //node and /descendant::node in xpath?

前端 未结 4 781
执念已碎
执念已碎 2020-12-14 15:34

I use a lot of XPath when locating elements in web pages using Selenium, and have moved away from using node1//node2 towards using node1/descendant::node2 more recently. Wha

相关标签:
4条回答
  • 2020-12-14 16:00

    see http://www.w3.org/TR/xpath#path-abbrev

    // is just an abbreviation for the descendant:: axis

    Edit

    To quote:

    //para is short for /descendant-or-self::node()/child::para

    That is, it refers to all para which are a child of the context node or any node descended from the context node. As far as I can tell that translates into any descendant para of the context node.

    0 讨论(0)
  • 2020-12-14 16:00

    In your case

     id('books')//td[@class='title']
    

    and:

     id('books')/descendant::td[@class='title']
    

    return the same result.

    But in fact, like it was already stated before, id('books')//td[@class='title'] means id('books')/descendant-or-self::node()/td[@class='title'] which is different from id('books')/descendant::td[@class='title'] in concept.

    See the following note:

    NOTE: The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.

    this note was taken from http://www.w3.org/TR/xpath#path-abbrev

    0 讨论(0)
  • 2020-12-14 16:08

    Other than terseness, I'm not aware of any difference.

    0 讨论(0)
  • 2020-12-14 16:18

    There's a difference in the context group. //para[1] is short for /descendant-or-self::node()/child::para[1], which returns every para that is the first child of its parent. /descendant::para[1] returns only the first para in the entire subtree.

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