Brian T Hannan
Brian T Hannan

Reputation: 4015

How can I shorten this XSLT snippet?

I have to repeat the following XSLT snippet like 100 times and I would like it to be as small as possible. Is there a way to make an equivalent XSLT snippet that is shorter?

<xslo:variable name="myVariable" select="//This/that/anotherthing" />
    <xslo:choose>
      <xslo:when test="string($myVariable) != 'NaN'">
        <xslo:text>1</xslo:text>
      </xslo:when>
      <xslo:otherwise>
        <xslo:text>0</xslo:text>
      </xslo:otherwise>
    </xslo:choose>

I'm basically setting the state of a checkbox based on whether or not a value exists in //This/that/anotherthing in the source xml.

Can be XSLT 1.0 or XSLT 2.0, doesn't matter.

Upvotes: 0

Views: 53

Answers (3)

michael.hor257k
michael.hor257k

Reputation: 117165

If I understand the purpose correctly - that is return 1 if the value in question can be successfully expressed as a number, 0 otherwise - then I believe:

<xsl:value-of select="number(//This/that/anotherthing castable as xs:double)"/>

would be the most straightforward way (in XSLT 2.0) to achieve it.


Edit

In view of your change of purpose:

I'm basically setting the state of a checkbox based on whether or not a value exists in //This/that/anotherthing

That's even simpler:

<xsl:value-of select="number(boolean(string(//This/that/anotherthing)))"/>

Upvotes: 0

Daniel Haley
Daniel Haley

Reputation: 52888

You can use an if instead of xsl:choose (XSLT 2.0 only)...

<xsl:value-of select="if (string(number(//This/that/anotherthing)) = 'NaN') then 0 else 1"/>

I also dropped the xsl:variable, but if you need it for some other reason, you can put it back.

You could also create a function...

<xsl:function name="local:isNumber">
    <xsl:param name="context"/>
    <xsl:value-of select="if (string(number($context)) = 'NaN') then 0 else 1"/>
</xsl:function>

usage...

<xsl:value-of select="local:isNumber(//This/that/anotherthing)"/>

Upvotes: 2

wero
wero

Reputation: 33010

<xslo:variable name="myVariable" select="//This/that/anotherthing" />
<xslo:value-of select="number(boolean($myVariable))"/>

Upvotes: 1

Related Questions