Conditional variable select in XSLT

Svish picture Svish · Oct 2, 2013 · Viewed 15.3k times · Source

I want a variable to have the value of an element if the value is numeric, but if it's not then I want the variable to have the value 0.

In other words, is there a simple equivalent of the following in XSLT?

var foobar = is_numeric(element value) ? element value : 0

Or how would you write this?

<xsl:variable name="foobar" select=" ? " />

Answer

kjhughes picture kjhughes · Oct 2, 2013

XPath 1.0:

<xsl:variable name="foobar">
  <xsl:choose>
    <xsl:when test="number($value) = number($value)">
      <xsl:value-of select="$value"/>
    </xsl:when>
    <xsl:otherwise>0</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

Reference for this clever number($value) = number($value) numeric test: Dimitre Novatchev's answer to "Xpath test if is number" question.