XSLT sets the default value if the selected value is not available

Is it possible to set the default value with <xsl:value-of> ? I am trying to create JSON output with an XSLT stylesheet, and some fields may not be available at processing time. This leaves a null value that violates the validity of the JSON document. Ideally, I could set a default if it is not available. So, in the case of:

  "foo_count": <xsl:value-of select="count(foo)" /> 

If <foo> not available in the document, can I somehow set this to 0?

+7
xml xslt
source share
3 answers

It either select

 <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 to invoke

 <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> 
+12
source share

XSLT / XPath 2

Using Sequence Expressions :

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

Description

One way to build a sequence is to use the comma operator, which evaluates each of its operands and combines the resulting sequences , in order, into a single sequence of results.

+14
source share

XSLT / XPath 2.0

You can use conditional expressions ( ifโ€ฆthenโ€ฆelse ) in the @select expression:

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

All Articles