在 XSLT 中,如何测试变量是否存在? [英] In XSLT how do you test to see if a variable exists?

查看:39
本文介绍了在 XSLT 中,如何测试变量是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 XSLT 时,您如何测试以查看局部范围的变量是否存在,或者这是否可能?

When using XSLT how do you test to see if a locally scoped variable exists, or is this even possible?

推荐答案

将 XSLT 样式表视为 XML DOM,变量声明元素使该变量对所有后续同级及其后代可见.这允许 XSLT 处理器静态分析任何包含变量引用的 XPath 以查看变量是否存在;如果变量声明存在于前兄弟轴或祖先轴上,则变量引用合法,否则不合法.

Considering the XSLT stylesheet as an XML DOM, a variable declaration element makes the variable visible to all following siblings and their descendants. This allows XSLT processors to statically analyze any XPath containing a variable reference to see if the variable exists; if the variable declaration exists on the preceding-sibling or ancestor axis, the variable reference is legal, otherwise it's not.

请注意,这完全取决于 XSLT 的结构,而不是它正在处理的 XML 的结构.如果 XPath 表达式使用不存在的变量,则 XSLT 处理器可以并且应该产生错误.

Note that this is entirely dependent on the structure of the XSLT, not the structure of the XML it's processing. The XSLT processor can and should produce an error if an XPath expression uses a variable that doesn't exist.

无法在 XSLT 中检查此条件,因为此条件在 XSLT 中不合法.您在评论中描述的情况 - 这个想法是在输出某些内容时设置一个标志变量,然后在没有输出任何内容时显示不同的消息."- 实际上应该导致语法错误.例如,如果您执行以下操作:

There's no way to check for this condition inside XSLT because this condition isn't legal within XSLT. The sitauation you described in your comment - "The idea is to set a flag variable if something is output and later on display a different message if nothing was output." - actually should result in a syntax error. For instance, if you do something like this:

<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 元素既不是变量声明的后续兄弟元素,也不是它们的后代元素之一.

you'll get a syntax error: the second xsl:if element is neither a following sibling of the variable declaration nor one of their descendants.

这是我经常使用的一种技术 - 这会根据您不想稍后重新检查的各种不同条件产生可变输出:

Here's a technique I use a fair amount - this produces variable output based on a variety of different conditions that you don't want to re-check later:

<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 中,如何测试变量是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆