2

I want to wrap any tag that contains a href attribute into an <a> tag.

eg.

<img src="someimage.jpg" href="someurl.xml"/>

would become:

<a href="someurl.xml"><img src="someimage.jpg"/></a>
Chris_F
  • 4,991
  • 5
  • 33
  • 63

2 Answers2

3
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <!--standard identity template that just copies content -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--For every element that has an href attribute-->
    <xsl:template match="*[@href]">
     <!--create an anchor element and an href attribute 
          with the value of the matched element's href attribute-->
        <a href="{@href}">
                   <!--then copy the matched element -->
            <xsl:copy>
                         <!--then apply templates (which will either match the 
                              identity template above or this template,
                              if any child elements have href attributes) -->
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </a>
    </xsl:template>

    <!--redact the href attribute-->
    <xsl:template match="*/@href"/>
</xsl:stylesheet>
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
0

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="*[@href]">
  <a href="{@href}">
   <xsl:copy>
     <xsl:apply-templates select=
         "node()|@*[not(name()='href')]"/>
   </xsl:copy>
  </a>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<img src="someimage.jpg" href="someurl.xml"/>

produces exactly the wanted, correct result (unlike the other answer):

<a href="someurl.xml">
   <img src="someimage.jpg"/>
</a>

Explanation: Identity rule, overriden for any element that has an href attribute.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431