tags:

views:

1372

answers:

3

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?

A: 

How about using fn:replace(string,pattern,replace) instead?

XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:

  <xsl:choose>
    <xsl:when test="condition1">
      condition1-statements
    </xsl:when>
    <xsl:when test="condition2">
      condition2-statements
    </xsl:when>
    <xsl:otherwise>
      otherwise-statements
    </xsl:otherwise>
  </xsl:choose>
Jonas Elfström
+1  A: 

The official language specification for XPath 2.0 on W3.org details that the language does indeed support if statements. See Section 3.8 Conditional Expressions, in particular. Along with the syntax format and explanation, it gives the following example:

if ($widget1/unit-cost < $widget2/unit-cost) 
  then $widget1
  else $widget2

This would suggest that you shouldn't have brackets surrounding your expressions (otherwise the syntax looks correct). I'm not wholly confident, but it's surely worth a try. So you'll want to change your query to look like this:

if (fn:ends-with(//div [@id='head']/text(),': '))
  then fn:substring-before(//div [@id='head']/text(),': ')
  else //div [@id='head']/text()

I do strongly suspect this may fix it however, as the fact that your XPath engine seems to be trying to interpret if as a function, where it is in fact a special construct of the language.

Finally, to point out the obvious, insure that your XPath engine does in fact support XPath 2.0 (as opposed to an earlier version)! I don't believe conditional expressions are part of previous versions of XPath.

Noldorin
I don't think it suggests you *shouldn't* use parentheses, only that you don't *need* to use them. If it's complaining about "no such function," then I suspect he's not using XPath 2. The spec requires parentheses around the conditional.
Rob Kennedy
@Rob: It's quite possible, but then I do state that it may not necessarily be the fix. Always worth following the example if you're trying to get something working, however. :)
Noldorin
But yeah, I missed the brackets around the condition somehow. Fixed now.
Noldorin
+4  A: 
Tomalak
I'll probably won't use this (I'll just upgrade the xpath engine) but this is a great trick and a great tip :)
yossale