如何用XSL检查一个值是空还是空?

例如,如果categoryName为空?我使用的是“当选择”结构。

例如:

<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>

当前回答

这对我来说很管用:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when> 
  <xsl:otherwise> 
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

或者反过来说:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when> 
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

注意:如果你不检查空值或不处理空值,IE7将返回-2147483648而不是NaN。

其他回答

实际上,我发现它更好的只是测试字符串长度,因为很多时候字段不是空的,只是空的

< xsl:当测试= " - length (field-you-want-to-test) < 1 >

在某些情况下,您可能想知道值什么时候具体为null,这在使用从. net对象序列化的XML时尤其必要。虽然接受的答案适用于此,但当字符串为空白或空时,它也返回相同的结果。,所以你无法区分。

<group>
    <item>
        <id>item 1</id>
        <CategoryName xsi:nil="true" />
    </item>
</group>

因此,您可以简单地测试属性。

<xsl:if test="CategoryName/@xsi:nil='true'">
   Hello World.
</xsl:if>

有时需要知道确切的状态,而不能简单地检查CategoryName是否已实例化,因为与Javascript不同

<xsl:if test="CategoryName">
   Hello World.
</xsl:if>

对于空元素将返回true。

这对我来说很管用:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when> 
  <xsl:otherwise> 
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

或者反过来说:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when> 
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

注意:如果你不检查空值或不处理空值,IE7将返回-2147483648而不是NaN。

关于什么?

test="not(normalize-space(categoryName)='')"

如果有可能元素在XML中不存在,我将测试元素是否存在以及字符串长度是否大于零:

<xsl:choose>
    <xsl:when test="categoryName and string-length(categoryName) &gt; 0">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>