2013-09-27 24 views
6

简化的例子:XSLT - 有没有一种方法,以追加到具有的<xsl:属性>添加属性?

<xsl:template name="helper"> 
    <xsl:attribute name="myattr">first calculated value</xsl:attribute> 
</xsl:template> 

<xsl:template match="/> 
    <myelem> 
    <xsl:call-template name="helper" /> 
    <xsl:attribute name="myattr">second calculated value</xsl:attribute> 
    </myelem> 
</xsl:template> 

有一些方法用于第二至追加的第二计算值,以在结果节点相同myattr属性?

我已经看到了这是可能的,如果目标属性是在源XML使用属性值模板,但我可以引用不知何故,我刚才添加到结果节点的属性值?

在此先感谢!

回答

4

您可以采取的一种方法是向您的助手模板添加一个参数,您将该参数附加到属性值。

<xsl:template name="helper"> 
    <xsl:param name="extra" /> 
    <xsl:attribute name="myattr">first calculated value<xsl:value-of select="$extra" /></xsl:attribute> 
</xsl:template> 

那么你可以过去你的第二个计算值作为参数

<xsl:template match="/> 
    <myelem> 
    <xsl:call-template name="helper"> 
     <xsl:with-param name="extra">second calculated value</xsl:with-param> 
    </xsl:call-template> 
    </myelem> 
</xsl:template> 

您不必设置虽然每次调用帕拉姆。如果你不希望任何附加,只是叫帮手模板,没有参数,并不会追加任何内容到第一计算值。

+0

好主意!还有一个问题:我可以在“helper”模板中添加更多参数,并可能在调用中使用更多的元素? –

+0

(回答我自己的问题:)是的,可以使用更多的参数。 –

0

试试这个:

<xsl:template name="helper"> 
    <xsl:attribute name="myattr">first calculated value</xsl:attribute> 
    </xsl:template> 
    <xsl:template match="/"> 
    <myelem> 
     <xsl:call-template name="helper" /> 
     <xsl:variable name="temp" select="@myattr"/> 
     <xsl:attribute name="myattr"> 
     <xsl:value-of select="concat($temp, 'second calculated value')" /> 
     </xsl:attribute> 
    </myelem> 
    </xsl:template> 
+3

这是行不通的 - 的'选择=“@ myattr”'看起来在输入树,而不是输出树的上下文节点。在这种情况下,该节点是不能具有任何属性的文档根节点('/')。 –

2

最简单的方法是改变排料一点 - 有helper刚刚生成的文本节点,并把<xsl:attribute>在调用模板:

<xsl:template name="helper"> 
    <xsl:text>first calculated value</xsl:text> 
</xsl:template> 

<xsl:template match="/> 
    <myelem> 
    <xsl:attribute name="myattr"> 
     <xsl:call-template name="helper" /> 
     <xsl:text>second calculated value</xsl:text> 
    </xsl:attribute> 
    </myelem> 
</xsl:template> 

这将设置myattr“先计算valuesecond计算值” - 如果你想“价值”和“第二”之间的空间中必须包括该<xsl:text>元素的内部,一个

 <xsl:text> second calculated value</xsl:text> 
+0

这是一个很好的答案,但在现实情况下,'helper'模板增加了更多的属性,以及''节点根据一定的计算可能会或可能不会修改'myattr'。所以,好主意,但在我的情况不方便。 –

0

虽然它或多或少同样的事情,我宁愿创建一个变量,而不是具有辅助模板的更简洁的方式。请注意,对于更复杂的情况,您仍然可以从xsl:variable内调用模板。

<xsl:template match="/"> 
    <myelem> 
    <xsl:variable name="first">first calculated value </xsl:variable > 
    <xsl:attribute name="myattr"> 
     <xsl:value-of select="concat($first, 'second calculated value')"/> 
    </xsl:attribute> 
    </myelem> 
</xsl:template> 
相关问题