2011-08-17 91 views

回答

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> 
+0

此轉換不會產生OP所需的結果。 –

+1

忘記處理'@ href'。答案已更新。 –

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屬性的元素。

相關問題