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=" ? " />
To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.
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!
You cannot - 'variables' in XSLT are actually more like constants in other languages, they cannot change value. Save this answer.
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With