gpt4 book ai didi

xslt - XSLT 中的变量范围

转载 作者:行者123 更新时间:2023-12-04 08:58:10 27 4
gpt4 key购买 nike

我在尝试找出 xslt 上的 var 范围时遇到问题。我实际上想要做的是忽略具有重复“旅游代码”的“旅行”标签。

示例 XML:

<trip>
<tourcode>X1</tourcode>
<result>Budapest</result>
</trip>
<trip>
<tourcode>X1</tourcode>
<result>Budapest</result>
</trip>
<trip>
<tourcode>X1</tourcode>
<result>Budapest</result>
</trip>
<trip>
<tourcode>Y1</tourcode>
<result>london</result>
</trip>
<trip>
<tourcode>Y1</tourcode>
<result>london</result>
</trip>
<trip>
<tourcode>Z1</tourcode>
<result>Rome</result>
</trip>

XSLT 处理器:
<xsl:for-each select="trip">    
<xsl:if test="not(tourcode = $temp)">
<xsl:variable name="temp" select="tour"/>
// Do Something (Print result!)
</xsl:if>
</xsl:for-each>

所需输出:
布达佩斯 伦敦 罗马

最佳答案

不能更改 XSLT 中的变量。

你需要多考虑一下 functional programming而不是过程性的,因为 XSLT 是一种函数式语言。想一想如下伪代码中的变量作用域:

variable temp = 5
call function other()
print temp

define function other()
variable temp = 10
print temp

你期望输出是什么?应该是 10 5 ,不是 10 10 ,因为 temp函数内部 othertemp 不是同一个变量在该功能之外。

在 XSLT 中也是如此。变量一旦创建,就无法重新定义,因为它们是设计一次写入、多次读取的变量。

如果您想有条件地定义变量的值,则需要有条件地定义变量,如下所示:
<xsl:variable name="temp">
<xsl:choose>
<xsl:when test="not(tourcode = 'a')">
<xsl:text>b</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>a</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:if test="$temp = 'b'">
<!-- Do something -->
</xsl:if>

变量只在一处定义,但它的值是有条件的。现在, temp的值已设置,以后无法重新定义。在函数式编程中,变量更像是只读参数,因为它们可以设置但不能在以后更改。您必须正确理解这一点才能在任何函数式编程语言中使用变量。

关于xslt - XSLT 中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2204555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com