Viktoriia Viktoriia - 3 months ago 8
Java Question

How to find elements which end with space and value by xpath

I tried to get all elements which end with symbol '3' like this

1 3

To do it I wrote this xpath

(//table)[2]//tr/td[position() = 7 and substring(., (string-length(.) - string-length(' 3')) + 2) = ' 3']


but it doesn't work.
P.S I try to rewrite function ends-with that is unavailable in xpath 1.0
Thanks.

Answer

The condition which you've written is incorrect. Try the condition below.

"... [position() = 7 and substring(., string-length(.) - string-length(' 3') + 1) = ' 3']"

Notice that I've changed the +2 to +1.

Have a look at the examples below:

> $x("substring('1 2 3', string-length('1 2 3') - string-length(' 3') + 2)")
"3"

> $x("substring('1 2 3', 5-2+2)")
"3"

Notice that the value of the second parameter to the substring function is 5. Hence, it returns the string from 5th index (Do note that in XPath the first index is considered as 1), i.e. "3".

To get " 3", simply add 1 instead of 2.

> $x("substring('1 2 3', string-length('1 2 3') - string-length(' 3') + 1)")
" 3"
Comments