2010-08-25 97 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