由于您使用的是XSLT 1.0,因此您可以使用string()
进行测试。
下面是一个例子样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<xsl:variable name="foo" select="bar"/>
<results>
<xsl:choose>
<xsl:when test="string($foo)">
<foo>DEFINED</foo>
</xsl:when>
<xsl:otherwise>
<foo>NOT DEFINED</foo>
</xsl:otherwise>
</xsl:choose>
</results>
</xsl:template>
</xsl:stylesheet>
需要注意的是空白被折叠,以便<bar> </bar>
将返回false。此外,string()
将在直接测试元素而不是变量时起作用。
这里的一些输入/输出例子:
输入
<test>
<bar/>
</test>
或
<test>
<bar></bar>
</test>
或
<test>
<bar> </bar>
</test>
输出
<foo>NOT DEFINED</foo>
输入
<test>
<bar>x</bar>
</test>
输出
<foo>DEFINED</foo>
如果您可以使用XSLT 2.0,则可以声明变量为xs:string
,并在测试中使用变量名称(test="$foo"
)。
实施例:
<xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xs">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<xsl:variable name="foo" select="bar" as="xs:string"/>
<results>
<xsl:choose>
<xsl:when test="$foo">
<foo>DEFINED</foo>
</xsl:when>
<xsl:otherwise>
<foo>NOT DEFINED</foo>
</xsl:otherwise>
</xsl:choose>
</results>
</xsl:template>
</xsl:stylesheet>
变量'foo'的变量定义之后定义。唯一的问题是它是否包含文本节点。 –
如果我问如何检查文本节点是否被定义的问题,它会更好吗? – randombits
如果输入包含“ ”或“ ”,您希望发生什么? –