2
我想將任何包含href屬性的標籤包裝到標籤中。使用XSLT包裝所有具有href屬性的元素
例如。
<img src="someimage.jpg" href="someurl.xml"/>
將成爲:
<a href="someurl.xml"><img src="someimage.jpg"/></a>
我想將任何包含href屬性的標籤包裝到標籤中。使用XSLT包裝所有具有href屬性的元素
例如。
<img src="someimage.jpg" href="someurl.xml"/>
將成爲:
<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>
這種轉變:
<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
屬性的元素。
此轉換不會產生OP所需的結果。 –
忘記處理'@ href'。答案已更新。 –