user_v12
user_v12

Reputation: 589

How check strings and numbers at once in xslt

I am trying to check strings and numbers at once in XSLT. Then I am getting the following error.

Cannot convert string "n/a" to double

Input :

<table>
  <tr>
    <td>0</td>
    <td>n/a</td>
    <td>3</td>
  </tr>
  <tr>
    <td>3</td>
    <td>7</td>
    <td>n/a</td>
  </tr>
</table>

Tried XSLT code:

<xsl:template match="table/tr">
  <xsl:choose>
    <xsl:when test="td[2] > 0">
      <xsl:value-of select="format-number(td[2] * 100,'0.00')"/>
    </xsl:when>
    <xsl:when test="td[2] = 'n/a'">
      <xsl:value-of select="'-'"/>
    </xsl:when>
    <xsl:when test="td[2] = 0">
      <xsl:value-of select="'-'"/>
    </xsl:when>
  </xsl:choose>
</template>

How can I fix this? I am using XSLT 2.0

Upvotes: 0

Views: 106

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117140

The simplest solution is to perform the test for "n/a" first - so that if it fails, the value must be a number (or at least so we assume):

<xsl:choose>
    <xsl:when test="td[2] = 'n/a'">
      <xsl:value-of select="'-'"/>
    </xsl:when>
    <xsl:when test="td[2] > 0">
      <xsl:value-of select="format-number(td[2] * 100,'0.00')"/>
    </xsl:when>
    <xsl:when test="td[2] = 0">
      <xsl:value-of select="'-'"/>
    </xsl:when>
</xsl:choose>

Upvotes: 2

Related Questions