2014-09-10 20 views
0

輸入XML:XSL複製模板,並添加新的屬性

<a> 
    <b1> 
     <c1 width="500" height="200"> 
      <d1 data="null" /> 
     </c1> 
    </b1> 
    <b2 /> 
</a> 

我想副本全部來自b1/c1屬性來b2/c1添加一個新屬性(length)。 輸出XML應該是:

<a> 
    <b1> 
     <c1 width="500" height="200"> 
      <d1 data="null" /> 
     </c1> 
    </b1> 
    <b2> 
     <c1 width="500" height="200" length="2"> 
      <d1 data="null" /> 
     </c1> 
    </b2> 
</a> 

我有個碼,其中複製所有從B1/c1至B2/C2 BUT 而不添加新atttribute(length):

<xsl:template match="https://stackoverflow.com/a/b2"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*" /> 
     <xsl:copy-of select="https://stackoverflow.com/a/b1/c1" /> 
     <xsl:apply-templates select="*" /> 
    </xsl:copy> 
</xsl:template> 

我試圖添加屬性到複製部分,但它不起作用:

<xsl:template match="https://stackoverflow.com/a/b2"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*" /> 
     <xsl:copy-of select="https://stackoverflow.com/a/b1/c1" > 
      <xsl:attribute name="length">2</xsl:attribute> 
     </xsl:copy-of> 
     <xsl:apply-templates select="*" /> 
    </xsl:copy> 
</xsl:template> 

回答

2

以標識模板開始,然後覆蓋b2節點。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 

    <xsl:strip-space elements="*"/> 

    <xsl:output indent="yes"/> 

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

    <xsl:template match="b2"> 
     <xsl:copy> 
      <xsl:apply-templates select="../b1/c1" mode="test"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="c1" mode="test"> 
     <xsl:copy> 
      <xsl:copy-of select="@*"/> 
      <xsl:attribute name="length">2</xsl:attribute> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 
+0

對不起,我編輯XML輸入:有在B2沒有C1,這就是爲什麼我需要複製的。那麼現在該怎麼做? – victorio 2014-09-10 10:46:05

+0

已編輯我的答案。 – 2014-09-10 10:51:18

+0

謝謝你,你救了我的載體! – victorio 2014-09-10 11:12:25

2

重新編輯過的問題 - 嘗試:

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

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

<xsl:template match="b2"> 
    <xsl:copy> 
     <xsl:apply-templates select="../b1/c1" mode="copy"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="c1" mode="copy"> 
    <xsl:copy> 
     <xsl:attribute name="length">2</xsl:attribute> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet>