我想检查变量是否有任何节点或任何属性。
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>
当我尝试运行上面的代码时,我得到“没有XML数据可用”。我需要检查变量具有任何节点/任何属性的天气,无论它是否有数据。
你能帮我解决这个问题。
答案 0 :(得分:0)
使用XSLT 1.0,您的变量的值为&#34;结果树片段&#34;,您需要使用扩展函数将其转换为首先设置的节点,以便能够寻址节点,例如
<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
。