tags:

views:

33

answers:

2

Hi,

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!

A: 

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')]">
Mario
Does not seem to work either... Thanks for trying though.
limburgie
+2  A: 

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"&gt;
    <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&lt;/xsl:attribute&gt;
    </xsl:template>
</xsl:stylesheet>

With this input:

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

Output:

<root>
    <a href="http://example.org"&gt;link&lt;/a&gt;
</root>

But, this stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <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&lt;/xsl:attribute&gt;
    </xsl:template>
</xsl:stylesheet>

Output:

<root>
    <a>link</a>
</root>
Alejandro
+1 for a good answer.
Dimitre Novatchev
Thanks, that did the trick!
limburgie
@limburgie: You are wellcome!
Alejandro