如何用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>

当前回答

来自Empty Element:

测试某个节点的值是否为空

这取决于你对空的定义。

不包含子节点:not(node()) 不包含文本内容:not(string(.)) 除空格外不包含任何文本:not(normalize-space(.)) 除了注释之外什么都不包含:not(node()[not(self::comment())])

其他回答

使用简单的categoryName/text()这样的测试工作良好<categoryName/>和<categoryName></categoryName>。

<xsl:choose>
    <xsl:when test="categoryName/text()">
        <xsl:value-of select="categoryName" />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

关于什么?

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

根据我的经验,最好的方法是:

<xsl:when test="not(string(categoryName))">
    <xsl:value-of select="other" />
</xsl:when>
<otherwise>
    <xsl:value-of select="categoryName" />
</otherwise>

在某些情况下,您可能想知道值什么时候具体为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:if test="USER/FIRSTNAME">
    USERNAME is not null
</xsl:if>
<xsl:if test="not(USER/FIRSTNAME)">
    USERNAME is null
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME=''">
     USERNAME is empty string
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME!=''">
     USERNAME is not empty string
 </xsl:if>