Paul Gu | Blog

sharing is caring

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())])

Next Post

Previous Post

1 Comment

  1. Asit April 30, 2021

    what if you want to check Null value?

Leave a Reply

© 2024 Paul Gu | Blog

Theme by Anders Norén