xsl:variable 作业说明

xsl:variable assignment clarification

我的理解是<xsl:variable>是不可变的,不能重新赋值。

我是 XSL 的新手,遇到过如下例所示的情况。

<xsl:stylesheet>

  <xsl:variable name="temp" select="true()"/>

  <xsl:template name="example">
     <xsl:variable name="temp" select="false()"/>
     <p><xsl:value-of select="$temp"/></p>
  </xsl:template>

</styleheet>

关于为什么会出现这种情况,我还没有找到任何确定的信息。我可以推断出我没有收到错误以及为什么 temp 会输出 false 的唯一方法是有一个全局 temp 变量和一个局部 temp 变量(并且不知何故没有发生碰撞)。

为什么我可以"reassign"temp?

My understanding is that is immutable and cannot be reassigned.

这个假设是正确的。 XSLT 是一种 functional language,不可变变量在这种语言中很常见。

Why am I able to "reassign" temp?

发生的原因由术语 Scope 定义。这意味着你对变量 temp overrides/overlays 的第二个定义是你的第一个 - 除非你离开它的范围 - 这里 - 模板。但是这里(正如@michael.hor257k 在评论中提到的那样)范围只能是样式表范围或模板范围 - 所以在同一个 xsl:template 中重新定义变量 - 即使在另一个代码块中 - 也是被禁止的.

The only way I can reason that I'm not getting an error and why temp will output false is that there is a global temp variable AND an a local temp variable

其实这两个变量都是局部的,只是在另一个层面上。第一个定义在 xsl:stylesheet 级别,第二个定义在 xsl:template 级别。第一个可能被认为是 global 变量,但这只是定义问题。

您可以 "reassign"(更准确地说,隐藏)变量,因为第一个绑定位于样式表的顶层,而第二个绑定位于模板中。

来自 XSLT 1.0 specification:

A binding shadows another binding if the binding occurs at a point where the other binding is visible, and the bindings have the same name. It is an error if a binding established by an xsl:variable or xsl:param element within a template shadows another binding established by an xsl:variable or xsl:param element also within the template. It is not an error if a binding established by an xsl:variable or xsl:param element in a template shadows another binding established by an xsl:variable or xsl:param top-level element.