在使用XSLT时,如何测试本地范围变量是否存在,或者这是否可能?
<xsl:if test="some_condition">
<!-- produce output here -->
<xsl:variable name="flag">true</xsl:variable>
</xsl:if>
<!-- time passes -->
<xsl:if test="$flag='true'>
<!-- wouldn't it be nice? -->
</xsl:if>
如果您使用的是第二个xsl:if
元素,而它既不是变量声明的后续同级元素,也不是其后代之一,则会出现语法错误。
这是我经常使用的一种技术 - 它可以根据各种不同的条件产生变量输出,而您不需要在以后重新检查它们:
<xsl:variable name="output">
<xsl:if test="$condition1='true'">
<p>condition1 is true</p>
</xsl:if>
<xsl:if test="$condition2='true'">
<p>condition2 is true</p>
</xsl:if>
<xsl:if test="$condition3='true'">
<p>condition3 is true</p>
</xsl:if>
</xsl:variable>
<!-- we've produced the output, now let's actually *output* the output -->
<xsl:copy-of select="$output"/>
<!-- time passes -->
<xsl:if test="normalize-space($output) != ''">
<p>This only gets emitted if $output got set to some non-empty value.</p>
</xsl:if>
询问这个问题表明您没有完全理解XSLT的关键点。:-)
XSLT是声明式的:除非您声明,否则任何东西都不存在。您声明一个变量,它就在那里;您不声明,它就不存在。
编码时不会有任何一点疑问,是否存在某个特定的变量。
XSLT具有严格的作用域规则,变量仅存在于其父元素的范围内(并非所有元素都能包含变量)。一旦离开父元素,该变量就消失了。
因此,除非您更明确地指定问题/意图,唯一有效的答案是该问题是错误的。您不需要在运行时检查变量是否存在。
XSL变量具有严格的作用域,因此您无法在同级节点中访问它们,只能在子节点中访问。
如果您正在处理参数,则可以使用全局 <xsl:param />
。
参见:http://www.stylusstudio.com/xsllist/199911/post30020.html
检查值是否存在的最佳且快速的方法是检查其长度
<xsl:if test="string-length(value/to/check)=0">
</xsl:if>
<xsl:choose>
<xsl:when test="$myvar">
This variable exists!
</xsl:when>
<xsl:otherwise>
The variable doesn't exist :(
</xsl:otherwise>
</xsl:choose>
至于它的有效性,我不能确定。但是我可以告诉你,在我们工作中的一些系统中,我确实这样做了 ;)