2013-09-27 29 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> 
相關問題