XSLT节点可用性检查



我想检查变量是否有任何节点或任何属性。

XSL:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
<xsl:template match="/">
    <xsl:variable name="testvar">
        <test><name first="Isaac" last="Sivakumar" middle="G"></name></test>
    </xsl:variable>
    <xsl:choose>
        <xsl:when test="normalize-space($testvar)">
            <xsl:value-of select="$testvar"></xsl:value-of>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="'NO XML DATA AVAILABLE'"></xsl:value-of>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

当我尝试运行上面的代码时,我得到"NO XML DATA available"。我需要检查一个变量是否有任何节点/任何属性,不管它是否有数据。

你能帮我解决这个问题吗?

使用XSLT 1.0,变量的值类型为"结果树片段",您需要使用扩展函数将其转换为节点集,以便能够对节点进行寻址,例如

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:exsl="http://exslt.org/common" version="1.0">
<xsl:template match="/">
    <xsl:variable name="testvar">
        <test><name first="Isaac" last="Sivakumar" middle="G"></name></test>
    </xsl:variable>
    <xsl:choose>
        <xsl:when test="exsl:node-set($testvar)/node()">
            <xsl:copy-of select="$testvar"></xsl:value-of>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="'NO XML DATA AVAILABLE'"></xsl:value-of>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

使用normalize-space或value-of没有多大意义,因为结果树片段中的XML在属性中包含所有数据,而没有包含数据的文本节点。

测试test="exsl:node-set($testvar)/node()"只是一个例子,它当然可以使用例如test="exsl:node-set($testvar)//name"来测试特定的元素,如name元素。

给定XSLT 1.0但EXSLT通用支持,最好检查http://www.exslt.org/exsl/functions/object-type/index.html例如

<xsl:choose>
  <xsl:when test="exsl:object-type($testvar) = 'string' and $testvar = ''">
    <xsl:value-of select="'NO XML DATA AVAILABLE'"/>
  </xsl:when>
  <xsl:when test="exsl:object-type($testvar) = 'node-set'">
    <xsl:copy-of select="$testvar"/>
  </xsl:when>
</xsl:choose>

对于XSLT 2.0,我将简单地检查例如if ($testvar instance of xs:string and $testvar = '') then 'NO XML DATA AVAILABLE' else $testvar

最新更新