Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath: Way to match text inside an arbitrary number of nested elements?

Tags:

html

xml

xpath

Is it possible for one XPath expression to match all the following <a> elements using the text in the element, in this case "Link"?

Examples:

  1. <a href="blah">Link</a>
  2. <a href="blah"><span>Link</span></a>
  3. <a href="blah"><div>Link</div></a>
  4. <a href="blah"><div><span>Link</span></div></a>
like image 205
StevieD Avatar asked Dec 24 '22 09:12

StevieD


1 Answers

This simple XPath expression,

//a[contains(., 'Link')]

will select the a elements of all of your examples because . represents the current node (a), and contains() will check the string value of a to see if it contains 'Link'. The string value of a already conveniently abstracts away from any descendent elements.

This even simpler XPath expression,

//a[. = 'Link']

will also select the a elements in all of your examples. It's appropriate to use if the string value of a will exactly equal, rather than just contain, "Link".

Note: The above expressions will also select <a href="blah">Li<br/>nk</a>, which may or may not be desirable.

like image 153
kjhughes Avatar answered Jan 01 '23 11:01

kjhughes