我想将包含href属性的任何标记包装到< a>标签
例如
<img src="someimage.jpg" href="someurl.xml"/>
会变成:
<a href="someurl.xml"><img src="someimage.jpg"/></a>
答案 0 :(得分: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>
答案 1 :(得分:0)
此转化:
<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>
应用于提供的XML文档:
<img src="someimage.jpg" href="someurl.xml"/>
产生完全想要的正确结果(与其他答案不同):
<a href="someurl.xml">
<img src="someimage.jpg"/>
</a>
说明: Identity rule ,覆盖任何具有href
属性的元素。