It seems with all the rich amount of function in xpath that you could do an “if” . However , my engine keeps insisting “there is no such function” , and I hardly find any documentation on the web (I found some dubious sources , but the syntax they had didn’t work)
I need to remove ‘:’ from the end of a string (if exist), so I wanted to do this:
if (fn:ends-with(//div [@id='head']/text(),': '))
then (fn:substring-before(//div [@id='head']/text(),': ') )
else (//div [@id='head']/text())
Any advice?
Yes, there is a way to do it in XPath 1.0:
This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false (
0 * string-length(...)), the second one being empty if the condition is true. This is called "Becker’s method", attributed to Oliver Becker (original link is now dead, the web archive has a copy).In your case:
concat( substring( substring-before(//div[@id='head']/text(), ': '), 1, number( ends-with(//div[@id='head']/text(), ': ') ) * string-length(substring-before(//div [@id='head']/text(), ': ')) ), substring( //div[@id='head']/text(), 1, number(not( ends-with(//div[@id='head']/text(), ': ') )) * string-length(//div[@id='head']/text()) ) )Though I would try to get rid of all the
"//"before.Also, there is the possibility that
//div[@id='head']returns more than one node.Just be aware of that — using
//div[@id='head'][1]is more defensive.