16

Sep

2011

Check if a string is null or empty in XSLT

Here is an example in different situations:

Sample XML:

<group>
    <item>
        <id>item 1</id>
        <CategoryName>blue</CategoryName>
    </item>
    <item>
        <id>item 2</id>
        <CategoryName></CategoryName>
    </item>
    <item>
        <id>item 3</id>
    </item>
    …
</group>

A sample use case would look like:

<xsl:for-each select="/group/item">
    <xsl:if test="CategoryName">
        <!– will be instantiated for item #1 and item #2 –>
    </xsl:if>
    <xsl:if test="not(CategoryName)">
        <!– will be instantiated for item #3 –>
    </xsl:if>
    <xsl:if test="CategoryName != ”">
        <!– will be instantiated for item #1 –>
    </xsl:if>
    <xsl:if test="CategoryName = ”">
        <!– will be instantiated for item #2 –>
    </xsl:if>
</xsl:for-each>

Conclusion:

To test if the value of a certain node is empty

It depends on what you mean by empty.

    * Contains no child nodes: not(node())
    * Contains no text content: not(string(.))
    * Contains no text other than whitespace: not(normalize-space(.))
    * Contains nothing except comments: not(node()[not(self::comment())])

Comments are closed.