2012-06-04 33 views
3

我有一個XML,我只想修改一個特定的部分,並將其餘的部分保留完好,這怎麼辦?即我只想修改節點AA2使用XSLT來轉換子節點,但保持其他節點不變

<root> 
    <parentHeader> 
    </parentHeader> 
    <body> 
    <ChildAA> 
     <AA1> 
     <foo>bar</foo> 
     <foo>bar2</foo>  
     </AA1> 
     <AA2> 
     <foo>bar</foo> 
     <foo>bar2</foo>  
     </AA2> 
    </ChildAA> 
    <ChildBB> 
     <BB1> 
     <foo>bar</foo> 
     <foo>bar2</foo> 
     </BB1> 
     <BB2> 
     <foo>bar</foo> 
     <foo>bar2</foo> 
     </BB2> 
    </ChildBB> 
    </body> 
</root> 

我有以下XSLT,它只返回修改後的部分。我怎樣才能包括其他一切?

<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="*"/> 

     <!-- Whenever you match any node or any attribute --> 
     <xsl:template match="/*"> 
      <xsl:apply-templates/> 
     </xsl:template> 


    <xsl:template match="AA2"> 
     <RenamedAA2>  
     <xsl:copy-of select="."/> 
     </RenamedAA2> 
    </xsl:template>  
    <xsl:template match="text()"/> 

</xsl:stylesheet> 

我期待這樣的事情作爲結果

<root> 
    <parentHeader> 
    </parentHeader> 
    <body> 
    <ChildAA> 
     <AA1> 
     <foo>bar</foo> 
     <foo>bar2</foo>  
     </AA1> 
    <RenamedAA2> 
     <foo>bar</foo> 
     </RenamedAA2> 
     <RenamedAA2> 
     <foo>bar2</foo>  
     </RenamedAA2> 
    </ChildAA> 
    <ChildBB> 
     <BB1> 
     <foo>bar</foo> 
     <foo>bar2</foo> 
     </BB1> 
     <BB2> 
     <foo>bar</foo> 
     <foo>bar2</foo> 
     </BB2> 
    </ChildBB> 
    </body> 
</root> 

回答

6

你想要什麼identity transform

您的模板發表評論Whenever you match any node or any attribute沒有達到您的想法。它只匹配根元素。

此外,你正在剝離所有text()節點與最後一個模板。

下面是你應該做的一個例子:

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output 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="AA2/foo"> 
     <RenamedAA2> 
      <xsl:copy> 
       <xsl:apply-templates select="node()|@*"/> 
      </xsl:copy> 
     </RenamedAA2> 
    </xsl:template> 

    <xsl:template match="AA2"> 
     <xsl:apply-templates/> 
    </xsl:template> 

</xsl:stylesheet> 

XML輸出

<root> 
    <parentHeader/> 
    <body> 
     <ChildAA> 
     <AA1> 
      <foo>bar</foo> 
      <foo>bar2</foo> 
     </AA1> 
     <RenamedAA2> 
      <foo>bar</foo> 
     </RenamedAA2> 
     <RenamedAA2> 
      <foo>bar2</foo> 
     </RenamedAA2> 
     </ChildAA> 
     <ChildBB> 
     <BB1> 
      <foo>bar</foo> 
      <foo>bar2</foo> 
     </BB1> 
     <BB2> 
      <foo>bar</foo> 
      <foo>bar2</foo> 
     </BB2> 
     </ChildBB> 
    </body> 
</root>