Home > Back-end >  Can ends-with() and text() be combined in XPath?
Can ends-with() and text() be combined in XPath?

Time:03-16

Already tried //*[ends-with(text()='updated the meeting')] and //*[ends-with(text(),'updated the meeting')] but did not work.

no element match

CodePudding user response:

You can use a normalize-space() method here:

//*[normalize-space() = 'updated the meeting']

or

//span[normalize-space() = 'updated the meeting']

The solutions above will work here, but in case there was some text before updated the meeting like more text presenting, updated the meeting you could use this:

//*[ends-with(normalize-space(text()), 'updated the meeting']

or this

//span[ends-with(normalize-space(text()), 'updated the meeting']

CodePudding user response:

Yes, ends-with() and text() can be used together in XPath, but...

  • No, it won't work the way you're trying.

  • No, using normalize-space() (as other answerers are offering) is not the way to work around the problem; such "solutions" do not test for the presence of a substring at the end of another string.

First issue: ends-with() requires XPath 2.0. If you're stuck with XPath 1.0, here's the (verbose) workaround.

Second issue: Even if your processor supports XPath 2.0, passing text() as its first argument is a mistake because ends-with() expects a string as its first argument, not a sequence of text nodes. This common confusion also occurs in XPath with the contains() function.

Therefore, to select all elements whose last text node child ends with 'updated the meeting', use this XPath 2.0 expression:

//*[text()[last()][ends-with(.,'updated the meeting')]]

To ignore any possible trailing whitespace:

//*[text()[last()][ends-with(normalize-space(),'updated the meeting')]]

Conversion of the above XPath 2.0 expressions to XPath 1.0 using this technique is left as an exercise.

CodePudding user response:

As shown in the picture, ends-with will not work. This is the text() value including the new lines and the quotes

xmllint --shell test.html 
/ > cat //div/span/text()
 -------

  " updated the meeting"
  

Adding normalize-space()

xmllint --xpath 'normalize-space(//div/span/text())'  test.html ; echo
" updated the meeting"

Using contains()

xmllint --xpath '//*[contains(normalize-space(text()), "updated the meeting")]'  test.html ; echo
<span>
  " updated the meeting"
  </span>
  • Related