0

我遇到了 xsl:templates 和 xsl:call-template 标签的问题。也许这是缺乏理解,但这是我想要做的......

如果我有一个在“/*”上匹配的模板,并且我需要从需要其他文档上下文的封闭模板中调用其他模板,那么最有效的方法是什么?

<xsl:template match="/*">

<xsl:call-template name="header">
  <xsl:with-param name="headerContext" select="./[1]"/>
</xsl:call-template>

<xsl:call-template name="body">
  <xsl:with-param name="bodyContext" select="*/*/[1]"/>
</xsl:call-template>

<xsl:template>

我在调用 header 和 body 模板时使用 xsl:with-param 以便我可以覆盖封闭模板中的 match="/*" ,但是当我这样做时,输出会变得混乱。如果我注释掉对“header”模板的调用,则正文模板可以正常工作,反之亦然,但是从主模板调用两者,如您在上面的示例中所见,会使它们的行为异常。标题和正文模板需要选择文档的不同部分,这就是我选择使用 w0th-param 的原因,但我认为它甚至不起作用。

我应该改用应用模板吗?

4

1 回答 1

0

XSL 被设计为基于事件的。因此,通常,您需要使用模板匹配,而不是明确指定要处理的后代。

<!-- Identity Template will copy every node to the output. -->
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<!-- You listed ./[1] as your xpath, but you might want to add more information 
   to make it more specific.  i.e. element names, not just * and position. -->
<xsl:template match="/*/header">
   <someOutputHeader><xsl:apply-templates /></someOutputHeader>
</xsl:template>

<xsl:template match="/something/*/body">
   <newBody><xsl:apply-templates /></newBody>
</xsl:template>

此外,在谓词之前指定 nodeTest 是一种很好的做法。因此,例如,您可以在斜杠之后指定 *,而不是写“./[1]”。“./*[1]” 你也不需要使用“./”。它是由 xpath 暗示的。所以真的,它是“* [1]”

于 2011-11-10T04:23:40.643 回答