Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional variable select in XSLT

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=" ? " />
like image 444
Svish Avatar asked Oct 02 '13 14:10

Svish


People also ask

How to write if condition in XSLT?

To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.

How do you set a global variable in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

Can we reassign a value to variable in XSLT?

You cannot - 'variables' in XSLT are actually more like constants in other languages, they cannot change value. Save this answer.


2 Answers

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.

like image 68
kjhughes Avatar answered Sep 24 '22 21:09

kjhughes


In XPath 2.0 yes, you can use "castable as"

<xsl:variable name="foobar" as="xs:double"
   select="if (x castable as xs:double) then x else 0" />
like image 30
Ian Roberts Avatar answered Sep 22 '22 21:09

Ian Roberts