Home > Net >  XPath: difference between "//*[contains(.,'sometext')]" and "//*[contains(t
XPath: difference between "//*[contains(.,'sometext')]" and "//*[contains(t

Time:11-25

I want to clearly understand what is the difference between the following XPath expressions "//*[contains(.,'sometext')]" and "//*[contains(text(),'sometext')]".
From enter image description here

This is why in my test your //*[contains(text(),'selenium')] query failed. Probably browsers have some work around for that to make things easier.

Now lets collapse that xml to get rid of that noise and look at the differences of approaches:

<test><node>selenium<node2>selenium</node2></node><node>selenium</node></test>

1. use text().

Here what https://www.freeformatter.com/xpath-tester.html returns:

Element='<node>selenium<node2>selenium</node2>
</node>'
Element='<node2>selenium</node2>'
Element='<node>selenium</node>'

Since //* defines all nodes within the tree here we have /test/node[1] that contains, also /test/node[1]/node2 and /test/node[2].

2. Now lets look at . case:

Now it returns:

Element='<test>
   <node>selenium<node2>selenium</node2>
   </node>
   <node>selenium</node>
</test>'
Element='<node>selenium<node2>selenium</node2>
</node>'
Element='<node2>selenium</node2>'
Element='<node>selenium</node>'

Why? because first of all /test is converted to seleniumseleniumselenium. Then /test/node[1] is converted to seleniumselenium, then /test/node[1]/node2 is converted to selenium and finally /test/node[2] is converted to selenium

So this makes the difference. Depending on how complex your nesting is, the results might show more or less significant difference between to approaches.

  • Related