XSL:如何为每个传递变量

时间:2013-07-01 17:43:17

标签: xslt-1.0

<xsl:for-each select="$script/startWith">
  <xsl:variable name = "i" > 
    <xsl:value-of select="$script/startWith[position()]"/>
  </xsl:variable>
  <xsl:for-each select="JeuxDeMots/Element">
    <xsl:variable name = "A" > 
      <xsl:value-of select="eName"/>
    </xsl:variable> 
    <xsl:if test="starts-with($A,$i)= true()">
      <xsl:variable name="stringReplace">
        <xsl:value-of select="substring($i,0,3)"/>
      </xsl:variable>
      <xsl:value-of select="$stringReplace"/>
    </xsl:if>
  </xsl:for-each>   
</xsl:for-each>

问题:变量$ i,无法传入xsl for-each。 请帮帮我。

2 个答案:

答案 0 :(得分:0)

尝试用

替换i的声明
<xsl:variable name="i" select="string(.)"/>

对于for-each指令的每个评估,上下文项(即“。”)是不同的,但表达式$script/startWith[position()]的值不会改变。 (这里,您正在创建一个startWith元素序列,并测试每个元素的表达式position()的有效布尔值。表达式position()返回一个正整数,因此它的有效布尔值值总是正确的。所以谓词[position()]在这里根本不起作用。

此外,您还需要将stringReplace的声明替换为

<xsl:variable name="stringReplace" select="substring($i,1,3)"/>

(字符串偏移量在XPath中以1开头,而不是0。)

我猜你想要处理startWith的所有$script个孩子,并为每个startWith值发出一次前三个字符,每个startWith / JeuxDeMots / Element,其eName子元素以startWith的值开头。

实际上,如果它更简洁直接,整个事情可能会更容易阅读:

<xsl:for-each select="$script/startWith">
  <xsl:variable name = "i" select="string()"/> 
  <xsl:for-each select="JeuxDeMots/Element">
    <xsl:if test="starts-with(eName,$i)">
      <xsl:value-of select="substring($i,1,3)"/>
    </xsl:if>
  </xsl:for-each>   
</xsl:for-each>

创建变量$ A和$ stringReplace是完全合理的,如果它们在你没有向我们展示的代码中多次使用,但如果没有,......

答案 1 :(得分:0)

我认为问题在于你首先要改变上下文。然后元素JeuxDeMots不是“可见”的第二个for-each。例如,您可以尝试将其存储在变量中,并在第二个for-each中使用此变量(还有另一种方法可以解决此问题)。

<xsl:template match="/">
    <xsl:variable name="doc" select="JeuxDeMots"/>

    <xsl:choose>
        <xsl:when test="$script/startWith">
            <xsl:for-each select="$script/startWith">
                <xsl:variable name="i">
                    <xsl:value-of select="."/>
                </xsl:variable>
                <xsl:for-each select="$doc/Element">
                    <xsl:variable name="A">
                        <xsl:value-of select="eName"/>
                    </xsl:variable>
                    <xsl:if test="starts-with($A,$i) = true()">
                        <xsl:variable name="stringReplace">
                            <xsl:value-of select="substring($i,0,3)"/>
                        </xsl:variable>
                        <xsl:value-of select="$stringReplace"/>
                    </xsl:if>
                </xsl:for-each>
            </xsl:for-each>
        </xsl:when>
    </xsl:choose>
</xsl:template>

虽然我不确定你究竟在处理什么,但它似乎输出了所需的值AsAt。

您还可以考虑C.M.Sperberg-McQueen关于XPath中字符串偏移的帖子。

相关问题