I want to wrap any tag that contains a href attribute into an <a> tag.
eg.
开发者_StackOverflow中文版<img src="someimage.jpg" href="someurl.xml"/>
would become:
<a href="someurl.xml"><img src="someimage.jpg"/></a>
<?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>
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.
精彩评论