2010-08-25 96 views
0

我制定了一個XSL模板,用於重寫HTML頁面上的所有超鏈接,其中包含href屬性中的特定子字符串。它看起來像這樣:重新創建XSL超鏈接而不重新創建元素

<xsl:template match="A[contains(@href, 'asp')]"> 
    <a> 
     <xsl:attribute name="href"> 
      <xsl:value-of select="bridge:linkFrom($bridge, $base, @href, 'intranet')" /> 
     </xsl:attribute> 
     <xsl:apply-templates select="node()" /> 
    </a> 
</xsl:template> 

我不喜歡這樣的事實,我必須從頭開始重新創建A元素。我知道你可以做這樣的事情:

<xsl:template match="A/@href"> 
    <xsl:attribute name="href"> 
     <xsl:value-of select="bridge:linkFrom($bridge, $base, ., 'intranet')" /> 
    </xsl:attribute> 
</xsl:template> 

但是我應該如何將這兩者合併在一起?我試過f.e.這並不起作用(元素沒有被選中):

<xsl:template match="A[contains(@href, 'asp')]/@href"> 
    <xsl:attribute name="href"> 
     <xsl:value-of select="bridge:linkFrom($bridge, $base, ., 'intranet')" /> 
    </xsl:attribute> 
</xsl:template> 

任何幫助,非常感謝!

回答

2

第一:如果你聲明的規則匹配的屬性,那麼你必須照顧應用模板到這些屬性,因爲沒有內置的規則,這樣做,並應用模板沒有選擇與apply-templates select="node()"相同。

所以,這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="a/@href[.='#']"> 
     <xsl:attribute name="href">http://example.org</xsl:attribute> 
    </xsl:template> 
</xsl:stylesheet> 

有了這個輸入:

<root> 
    <a href="#">link</a> 
</root> 

輸出:

<root> 
    <a href="http://example.org">link</a> 
</root> 

但是,這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="a/@href[.='#']"> 
     <xsl:attribute name="href">http://example.org</xsl:attribute> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

<root> 
    <a>link</a> 
</root> 
+0

+1一個很好的答案。 – 2010-08-25 13:38:46

+0

謝謝,那就是訣竅! – 2010-08-25 14:08:51

+0

@limburgie:你好! – 2010-08-25 15:00:52

0

我也期待它的工作。我現在沒有辦法測試這個,但是你是否嘗試過其他方式來編寫它? 例如:

<xsl:template match="A/@href[contains(. , 'asp')]"> 
+0

似乎無法正常工作...感謝您嘗試。 – 2010-08-25 11:37:49