2013-03-08 61 views
0

我有以下XSL模板:XSLT的xsl:副本的xsl:for-各有關屬性

<xsl:template match="@*|node()" mode="fix-entity-references"> 
    <xsl:copy> 
     <xsl:for-each select="@*"> 
      <xsl:if test="name() = 'href'"> 
       <xsl:variable name="hrefvar"> 
       <xsl:value-of select="current()"/> 
       </xsl:variable> 
       <xsl:attribute name="href"> 
       anything 
       </xsl:attribute> 
      </xsl:if> 
     </xsl:for-each> 
     <xsl:apply-templates select="@*|node()" mode="fix-entity-references"/> 
    </xsl:copy> 
    </xsl:template> 

我想用這個模板複製當前節點,但只能處理這一切後的屬性。目前的樣本非常簡單,可以用一個非常簡單的塊代替。測試表達式會更加複雜,重點在於每個滿足表達式的元素都可以有N個屬性。這就是爲什麼每個都是必要的。我想以同樣的方式處理所有這些屬性。我試圖打印「當前()」值,它始終正常工作。問題在於更新原始節點的屬性。將「href」屬性的值設置爲「anything」是行不通的,因爲我猜測在我調用它的時候,它位於for-each塊內,這意味着當前節點是屬性本身。

我應該如何在for-each塊中設置原始塊的屬性,以便複製的節點將使用修改後的屬性?

預先感謝您。

回答

1

而不是for-eachif,您可能會考慮使用與您想要以不同方式處理的屬性相匹配的模板。

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

<xsl:template match="@href | @foo | @bar" mode="fix-entity-references"> 
    <xsl:attribute name="{name()}"> 
    <xsl:value-of select=".."/> 
    </xsl:attribute> 
</xsl:template> 

在XPath數據模型的屬性節點不被認爲是元素的子元素,但屬性節點的父是元素,屬性屬於(即,當上下文節點是一個屬性,..是可以在其上找到屬性的元素)。因此,這個樣本將替換屬性的包含元素的文本內容的任何hreffoobar屬性的值,即

<a href="#">http://example.com</a> 

將成爲

<a href="http://example.com">http://example.com</a> 
+0

我喜歡它了很多先生謝謝! – 2013-03-08 11:52:01