tags:

views:

36

answers:

4

I have a simple XML, that I want to add a new root to. The current root is <myFields> and I want to add <myTable> so it would look like.

<myTable>
    <myFields>
    .
    .
    </myFields>
</myTable>
+2  A: 

Something like this should work for you...

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

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>
Ryan Berger
almost works, but there are not longer any child elements, only values
Marsharks
hang on, I'll fix it :)
Ryan Berger
@Marsharks and @Ryan Berger: Do note that this outputs strange results when there is some PI before root element...
Alejandro
yes, I saw that. Mine is an InfoPath form. My solution works for me.
Marsharks
A: 

you helped get me close enough

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:template match="/">
        <xsl:element name="myTable">
            <xsl:copy-of select="*" />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>
Marsharks
If you care to preserve any comments or processing-instructions that might be before the document element, then @Ryan Berger's solution is the way to go.
Mads Hansen
+1  A: 

This is probably the shortest solution :) :

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

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <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>

Note: Copy everything (also PIs before root element), and add myTable befere root element.

Alejandro