Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying default values if a node does not exist

Tags:

xml

xslt

I am currently using this construct to assign default values if a node does not exist in a supplied XML doc. Is there a more concise way of stating the same thing?

<xsl:choose>
  <xsl:when test="var_name"><xsl:value-of select="var_name"/></xsl:when>
  <xsl:otherwise>default</xsl:otherwise>
</xsl:choose>
like image 493
rophl Avatar asked Aug 31 '26 15:08

rophl


1 Answers

I. XPath 2.0

Use:

concat($yourVar, 'default'[not($yourVar)])

Here is a complete XSLT 2.0 transformation:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="yourVar" select="'something'"/>
 <xsl:variable name="yourVar2" select="''"/>

 <xsl:template match="/">
  <xsl:sequence select="concat($yourVar, 'default'[not($yourVar)])"/>
  <xsl:text>&#xA;</xsl:text>
  <xsl:sequence select="concat($yourVar2, 'default'[not($yourVar2)])"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the wanted strings are produced and output for both variables:

something
default

II. XPath 1.0

Use:

concat($yourNodeExpr, 
       substring('default', 1 + 7*boolean($yourNodeExpr)))

This produces the string value of $yourNodeExpr if it contains at least one node, otherwise it produces the string "default".

Explanation:

We use the fact that:

In XPath 1.0 whenever a boolean value is an operand of an arithmetic operator, this value is converted to a number: number(false()) = 0 and number(true()) = 1. Thus, if boolean($yourNodeExpr) is true() the second argumend to substring above will become1+7 = 8` and the substring will be the empty string.

On the other side, if boolean($yourNodeExpr) is false(), the second argument to substring() is 1+0 = 1 and the substring is the string "default"

A more general expression:

concat(substring($val1, 1 div $cond1),
       substring($val1, 1 div $cond2)
       )

Assuming that the the two conditions $cond1 and $cond2 are mutually exclusive (($cond1 and $cond2) = false() and ($cond1 or $cond2) = true() ) then the above expression produces the string $val1 when $cond1 is true() and produces the string $val2 when $cond2 is true().

like image 105
Dimitre Novatchev Avatar answered Sep 03 '26 04:09

Dimitre Novatchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!