How can I check if a value is null or empty with XSL?
For example, if categoryName
is empty? I\'m using a when choosing construct.
For
In some cases, you might want to know when the value is specifically null, which is particularly necessary when using XML which has been serialized from .NET objects. While the accepted answer works for this, it also returns the same result when the string is blank or empty, i.e. '', so you can't differentiate.
<group>
<item>
<id>item 1</id>
<CategoryName xsi:nil="true" />
</item>
</group>
So you can simply test the attribute.
<xsl:if test="CategoryName/@xsi:nil='true'">
Hello World.
</xsl:if>
Sometimes it's necessary to know the exact state and you can't simply check if CategoryName is instantiated, because unlike say Javascript
<xsl:if test="CategoryName">
Hello World.
</xsl:if>
Will return true for a null element.
Use simple categoryName/text() Such test works fine on <categoryName/>
and also <categoryName></categoryName>
.
<xsl:choose>
<xsl:when test="categoryName/text()">
<xsl:value-of select="categoryName" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="other" />
</xsl:otherwise>
</xsl:choose>