代码之家  ›  专栏  ›  技术社区  ›  Niels van der Rest

XSL模板处理所有子体,而不仅仅是子体

  •  1
  • Niels van der Rest  · 技术社区  · 15 年前

    考虑到下面的XML和XSL转换,我希望有两种 <node/> first second . 这一期望基于以下推理:

    1. 模板 match="/root" 将首先执行。这个 <xsl:apply-templates/> 此模板中的说明将应用最具体的模板 for all child nodes .
    2. <foo/> 子节点将由第二个模板处理。此模板还包含 <xsl:apply-templates/> 指令,将模板应用于这些节点的子节点。
    3. 这个 < 节点仅包含 <bar/>

    XML格式

    <?xml version="1.0" encoding="utf-8"?>
    <?xml-stylesheet type="text/xsl" href="style.xsl"?>
    <root>
      <foo name="first">
        <bar>
          <foo name="nested"/>
        </bar>
      </foo>
      <foo name="second">
        <bar>
          <baz>
            <foo name="nested"/>
          </baz>
        </bar>
      </foo>
    </root>
    

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:template match="/root">
        <output>
          <xsl:apply-templates/>
        </output>
      </xsl:template>
      <xsl:template match="foo">
        <node>
          <xsl:value-of select="@name"/>
        </node>
        <xsl:apply-templates/>
      </xsl:template>
    </xsl:stylesheet>
    

    然而,上述转换的实际结果包含四个方面 <节点/> nested . 这意味着第二个模板也应用于最内部的 <foo/>

    我在多个web浏览器中测试了转换,并使用Notepad++XML工具插件,结果都是“错误的”。所以我想我错了,但是 我的推理有什么问题?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Woody    15 年前

    但是条形图节点与模板匹配,它们与内置的“*”模板匹配,后者传播模板,调用内部条形图/节点模板

        2
  •  1
  •   Oded    15 年前

    <xsl:template match="foo">
    

    这和 foo 元素,不管它们的嵌套级别如何 apply-templates ,全部

    这个 built in template rules 也会导致 bar 要匹配的节点。