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

当前回答

如果有可能元素在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>

其他回答

来自Empty Element:

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

这取决于你对空的定义。

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

关于什么?

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

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

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

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

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

如果一个节点在输入xml中没有可用的值,比如xpath,

<node>
    <ErrorCode/>
</node>

String()函数转换为空值。所以这很好:

string(/Node/ErrorCode) =''