Skip to content

Instantly share code, notes, and snippets.

@ijy
Created September 15, 2013 17:14
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ijy/6572634 to your computer and use it in GitHub Desktop.
Save ijy/6572634 to your computer and use it in GitHub Desktop.
XSLT: Check if a string is null or empty.
<!--
CHECK IF A STRING IS NULL OR EMPTY
-->
<!-- Example 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>
<!-- Example test case -->
<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>
<!--
To test if the value of a certain node is empty it depends on what is meant 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())])
-->
@ibdiestre
Copy link

Hi.

Thanks very much for this information:
* Contains no text content: not(string(.))

That helped me a lot in a code for which I wanted to run a for-each select, and in case nothing was selected I wanted to run a second for-each select. Now I've put a condition to the second and is only running in case the first one failed

Thanks again.

@carlos26102
Copy link

Great, Thanks a lot. Continue this way...

@SwapnaGundlapally
Copy link

I am unable to test for empty string using my below code

<xsl:if test="Name != ''">

I am getting below error
One or more errors occurred. (String literal was not closed.
Name != -->'<-- )

Can you please suggest

@antoniomolinabravo
Copy link

<xsl:if test="number($Name) > 0"> this is ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment