Difference between "//" and "/" in XPath?

I tried to use XPath for python-selenium.

I used this link to test some XPaths from the tutorials:

So, I tried these two XPaths options.

  • This expression

    //webengagedata//preceding-sibling::*
    
          

returned 14 results

  1. And this expression

    //webengagedata/preceding-sibling::*
    
          

returned 9 results

What does "//" do to get 5 more results?

+3


source to share


3 answers


/

vs //

in general

Both child

( /

) and descendant-or-self

( //

) are axes in XPath .

  • /

    shortened for /child::node()/

    .

    Use /

    to select child nodes.

  • //

    shortened for /descendant-or-self::node()/

    .

    Use //

    to select a node, its children, its grandchildren, etc. recursively.


/

vs //

withpreceding-sibling::*



Your specific question brings up the difference between //preceding-sibling::*

and /preceding-sibling::*

.

Since your data is remote and complex, consider this and simpler XML instead:

<r>
  <a/>
  <b>
    <c/>
    <d/>
  </b>
</r>

      

For this XML

  • /r/preceding-sibling::*

    chooses nothing because he r

    has no previous siblings.
  • /r//preceding-sibling::*

    selects previous sibling elements of all descendants or native nodes r

    . Ie a

    , b

    , c

    and d

    . (Remember, /r//preceding-sibling::*

    not good for /descendant-or-self::node()/preceding-sibling::*

    , not /descendant-or-self::*/preceding-sibling::*

    ). Note that even though b

    they d

    are no-element siblings, they are text nodes siblings because the above XML has spaces after b

    and d

    . If spaces are removed, only b

    and will be selected d

    .
  • /r/descendant::*/preceding-sibling::*

    selects the previous siblings of all descendant elements r

    . That is a

    and c

    . Note that b

    and are d

    not selected because they do not precede sibling elements for any descendant elements r

    - unlike the previous example, text nodes do not match the criteria.
+6


source


For your example

//webengagedata/preceding-sibling::* ---> returned 9 results

      

Since there are only 9 tags that are exact tag affinity webengagedata

, so it shows 9 entries



//webengagedata//preceding-sibling::* ---> returned 14 results

      

Here it looks at child tags and also biziclop said x/descendant-or-self::node()/y

+1


source


The difference is what x//y

is shorthand for x/descendant-or-self::node()/y

.

What all.

So, while the first query selects all descendants <webengagedata>

that have another tag after them, the second only selects the preceding siblings of the tag itself.

The xpath shorthand syntax rules are explained here .

0


source







All Articles