tags:

views:

20985

answers:

3

how chan i check if a value is null or empty with xsl?

eg if categoryName is empty? im using a when choose construct

eg:

 <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>
+10  A: 
test="categoryName != ''"
steamer25
The detailed semantics of this test is: return true if there is at least one categoryName element whose string value is an empty string.
jelovirt
+5  A: 

From here:

to test if the value of a certain node is empty

Depends 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())])
Chris Doggett
+15  A: 

Absent of any other information, I'll assume the following 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>
johnvey
Nice to explain the different cases. However, your example is misleading as only the first `xsl:when` whose test evaluates to `true()` will be matched, i.e. case 3 and 4 will never match because already case 1 has matched.
0xA3
(continued) See http://www.w3.org/TR/xslt#section-Conditional-Processing-with-xsl:choose: "The content of the first, and only the first, xsl:when element whose test is true is instantiated."
0xA3
I changed the sample to something more meaningful.
0xA3