3

I have this HTML:

<div>
    I
    <span> need</span>
    this
    <span> text</span>
</div>

I want to find this div, looking at what text have inside (concatenate all text).

Something like: //div[text() = 'I need this text'], but of course, it not work.

How I can done this?

KunLun
  • 3,109
  • 3
  • 18
  • 65

3 Answers3

4

Try using normalize-space()...

//div[normalize-space() = 'I need this text']
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • 1
    Good answer (+1). See also [Testing text() nodes vs string values in XPath](https://stackoverflow.com/q/34593753/290085) for why OP's `text()`-based predicate failed. – kjhughes Nov 26 '19 at 18:04
1

Your attempt is close; try this expression:

div[normalize-space(string-join(.//text(),''))='I need this text']

The expression first joins all the text nodes in the element, then strips spaces from the joined string and finally looks for an element (div in this case) which has the property that the normalized string of its text nodes is equal to the target string.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • 1
    Good call using normalize-space() (we answered at the same time). You don't need the string-join() though; normalize-space defaults to using the string-value of the context node. Also, string-join() is only available in xpath 2.0+. – Daniel Haley Nov 26 '19 at 17:02
  • 1
    @DanielHaley - Yup; I realized this now after trying your solution; live and learn! – Jack Fleeting Nov 26 '19 at 17:13
0

this should help you

//div[. = 'I need this text']