XSL在另一个模板中使用特定模板

时间:2010-10-29 07:30:20

标签: templates xslt

我遇到了一些XSL问题:当它使用apply-templates打印孩子时,是否可以使用另一个模板?我不想使用当前节点,但实际上创建了一个与模板匹配的新元素。

我正在搜索的例子:

XML文件:

<root>
  <toto name="foo">
    <b>hello</b>
  </toto>
</root>

XSL样式表:

<xsl:template match="/">
  <xsl:apply-templates />
</xsl:template>

<xsl:template match="tata" name="tata">
  <div class="tata">
    <xsl:apply-templates />
  </div>
</xsl:template>

<xsl:template match="toto" name="toto">
  <tata>
    <xsl:value-of select="@name" />
  </tata>
  <tata>
    <xsl:apply-templates />
  </tata>
</xsl:template>

<xsl:template match="@*|node()">
   <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
   </xsl:copy>
</xsl:template>

预期输出:

<div class="tata">foo</div>
<div class="tata">
  <b>hello</b>
</div>

2 个答案:

答案 0 :(得分:2)

如果我理解正确你正在寻找

<xsl:call-template name="tata" />

元素。

答案 1 :(得分:0)

您无需在问题中调用其他模板。您几乎可以在template match="toto"中完成所有必需的处理。事实上,在您的示例代码中,<xsl:template match="tata">从未使用过(使用给定的输入XML)。在模板中创建文字元素不会导致调用与该元素匹配的另一个模板。

此样式表

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

    <xsl:output encoding="UTF-8" indent="yes"/>

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

    <xsl:template match="toto">
        <div class="tata">
            <xsl:value-of select="@name"/>
        </div>
        <div class="tata">
            <xsl:apply-templates/>
        </div>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

使用此输入

<root>
  <toto name="foo">
    <b>hello</b>
  </toto>
</root>

产生所需的结果

<?xml version="1.0" encoding="UTF-8"?>
<div class="tata">foo</div>
<div class="tata">
<b>hello</b>
</div>

与Dennis一样,如果您想使用另一个模板,请使用<xsl:call-template/>元素。如果您还想更改当前节点(上下文节点),可以使用

<xsl:apply-templates select="path/to/new/context"/>
相关问题