XSLT set default value when selected one is not available

It is either choose

<xsl:choose>
   <xsl:when test="foo">
     <xsl:value-of select="count(foo)" />
   </xsl:when>
   <xsl:otherwise>
     <xsl:text>0</xsl:text>
   </xsl:otherwise>
 </xsl:choose> 

or use if test

<xsl:if test="foo">
  <xsl:value-of select="count(foo)" />
</xsl:if>
<xsl:if test="not(foo)">
  <xsl:text>0</xsl:text>
</xsl:if>

or use a named template for calling

<xsl:template name="default">
  <xsl:param name="node"/>
  <xsl:if test="$node">
      <xsl:value-of select="count($node)" />
    </xsl:if>
    <xsl:if test="not($node)">
      <xsl:text>0</xsl:text>
  </xsl:if>
</xsl:template>

 <!-- use this in your actual translate -->
 <xsl:call-template name="default">
         <xsl:with-param name="node" select="."/>
 </xsl:call-template>

XSLT/XPath 2

Using Sequence Expressions:

<xsl:value-of select="(foo,0)[1]"/>

Explanation

One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.


XSLT/XPath 2.0

You can use a Conditional Expressions (if…then…else) on your @select expression:

<xsl:value-of select="if (foo) then foo else 0" />

Tags:

Xml

Xslt