How can I check if a value is null or empty with XSL?
For example, if
categoryName
is empty?
This is probably the simplest XPath expression (the one in accepted answer provides a test for the opposite, and would be longer, if negated):
not(string(categoryName))
Explanation:
The argument to the not()
function above is false()
exactly when there is no categoryName
child ("null") of the context item, or the (single such) categoryName
child has string value -- the empty string.
I'm using a when choosing construct.
For example:
<xsl:choose> <xsl:when test="categoryName !=null"> <xsl:value-of select="categoryName " /> </xsl:when> <xsl:otherwise> <xsl:value-of select="other" /> </xsl:otherwise> </xsl:choose>
In XSLT 2.0 use:
<xsl:copy-of select="concat(categoryName, $vOther[not(string(current()/categoryName))])"/>
Here is a complete example:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vOther" select="'Other'"/>
<xsl:template match="/">
<xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the following XML document:
<categoryName>X</categoryName>
the wanted, correct result is produced:
X
When applied on this XML document:
<categoryName></categoryName>
or on this:
<categoryName/>
or on this
<somethingElse>Y</somethingElse>
the correct result is produced:
Other
Similarly, use this XSLT 1.0 transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vOther" select="'Other'"/>
<xsl:template match="/">
<xsl:copy-of select=
"concat(categoryName, substring($vOther, 1 div not(string(categoryName))))"/>
</xsl:template>
</xsl:stylesheet>
Do note: No conditionals are used at all. Learn more about the importance of avoiding conditional constructs in this nice Pluralsight course: