dowdw44426
dowdw44426
2013-05-25 17:18
浏览 38
已采纳

为什么不能在XSL模板选择器谓词中使用变量?

Given this XML;

<root>
  <foo x='1'/>
  <foo x='3'/>
  <foo x='7'/>
</root>

and this stylesheet;

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="root">
    <result>
      <xsl:apply-templates select="foo"/>
    </result>
  </xsl:template>

  <xsl:template match="foo[@x > 2]">
    <xsl:copy-of select="."/>
  </xsl:template>

</xsl:transform>

I get the desired result;

<result>
  <bar x="3"/>
  <bar x="7"/>
</result>

But if the template match for foo is changed to use a variable $i instead of a constant;

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:variable name="i" select="2"/>  

  <xsl:template match="root">
    <result>
      <xsl:apply-templates select="foo"/>
    </result>
  </xsl:template>

  <xsl:template match="foo[@x > $i]">
    <xsl:copy-of select="."/>
  </xsl:template>

</xsl:transform>

then I get this error;

XSLTProcessor::importStylesheet(): compilation error: Failed to compile predicate

Am I doing something wrong or can't variables be used in that way?

I have tried declaring the variable in other ways eg;

  <xsl:variable name="i" select="2"/>
  <xsl:variable name="i">2<xsl:variable>

but it always fails to compile the stylesheet.

I'm using the PHP XSL 1.0 processor libxslt;

PHP Version      5.3.2
libxslt Version  1.1.23
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougu3988
    dougu3988 2013-05-28 22:46
    已采纳

    No, variables cannot be referred to in template match patterns (or in xsl:key instructions).

    Why not? Because the declaration of a variable is allowed to contain a call to xsl:apply-templates -- so allowing variable references in template match patterns would make circular variable declarations possible.

    点赞 评论

相关推荐