开发者

XSL hyperlink rewriting without recreating the element

I worked out an XSL template that rewrites all hyperlinks on an HTML page, containing a certain substring in the href attribute. It looks like this:

<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>

I'm not liking the fact that I must recreate the A element from scratch. I know you can do something like this:

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

But how should I merge these two together? I tried f.e. this and it doesn't work (the element does not get selected):

<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>

Any help is much appreciated!


First: If you declare a rule for matching an attribute, then you must take care of apply templates to those attributes, because there is no built-in rule doing that and apply templates without select is the same as apply-templates select="node()".

So, this stylesheet:

<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>

With this input:

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

Output:

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

But, this stylesheet:

<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>

Output:

<root>
    <a>link</a>
</root>


I would also expect it to work. I have no way of testing this now but did you try any other way of writing it? For example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜