2010-10-22 72 views
2

我有一個簡單的XML,我想添加一個新的根。當前的根目錄是<myFields>,我想添加<myTable>,所以它看起來像。如何使用XSLT將頂級元素添加到XML?

<myTable> 
    <myFields> 
    . 
    . 
    </myFields> 
</myTable> 
+0

好問題,+1。查看我的答案,找出最可能的最短解決方案。 :)這也是正確的! – 2010-10-22 19:13:18

回答

4

像這樣的東西應該爲你工作...

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

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

幾乎可以工作,但不再有任何子元素,只有值 – Marsharks 2010-10-22 17:48:02

+0

掛上,我會修復它:) – 2010-10-22 17:50:07

+0

@Marsharks和@Ryan Berger:請注意,當根元素之前存在PI時,會輸出奇怪的結果。 – 2010-10-22 19:38:42

0

你幫我弄足夠接近

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
     <xsl:element name="myTable"> 
      <xsl:copy-of select="*" /> 
     </xsl:element> 
    </xsl:template> 
</xsl:stylesheet> 
+0

如果您關心的是保留文檔元素之前的任何註釋或處理指令,那麼@Ryan Berger的解決方案就是您的選擇。 – 2010-10-22 18:34:06

1

這可能是最短的解決方案 :):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
     <myTable> 
      <xsl:copy-of select="node()" /> 
     </myTable> 
    </xsl:template> 
</xsl:stylesheet> 
1

這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/*"> 
     <myTable> 
      <xsl:call-template name="identity"/> 
     </myTable> 
    </xsl:template> 
    <xsl:template match="@*|node()" name="identity"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

注意:複製一切(也督察根元素前),並添加myTable befere 根元素