Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

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

I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

  1. This expression

    //webengagedata//preceding-sibling::*
    

returned 14 results

  1. And this expression

    //webengagedata/preceding-sibling::*
    

returned 9 results

What does the "//" do to match 5 more results?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

/ vs // in general

Both child (/) and descendant-or-self (//) are axes in XPath.

  • / is short for /child::node()/.

    Use / to select a node's immediate children.

  • // is short for /descendant-or-self::node()/.

    Use // to select a node, its children, its grandchildren, and so on recursively.


/ vs // with preceding-sibling::*

Your specific question asks about the difference between //preceding-sibling::* and /preceding-sibling::*.

Since your data is offsite and complex, let's consider instead this present and simpler XML:

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

For this XML,

  1. /r/preceding-sibling::* selects nothing because r has no preceding siblings.
  2. /r//preceding-sibling::* selects the preceding siblings elements of all of the descendant or self nodes of r. That is, a, b, c and d. (Remember, /r//preceding-sibling::* is short for /descendant-or-self::node()/preceding-sibling::*, not /descendant-or-self::*/preceding-sibling::*) Note that even though b and d are predecessor siblings to no elements, they are predecessor siblings to text nodes because the above XML has whitespace after b and d. If all whitespace were removed, then only a and c would be selected.
  3. /r/descendant::*/preceding-sibling::* selects the preceding sibling elements of all descendant elements of r. That is, a and c. Note that b and d are not selected because they are not preceding sibling elements to any descendant elements of r -- unlike the previous example, text nodes do not qualify.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...