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>
1
  • Good question, +1. See my answer for the most likely shortest solution. :) It is also correct! Commented Oct 22, 2010 at 19:13

4 Answers 4

6

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>
Sign up to request clarification or add additional context in comments.

3 Comments

almost works, but there are not longer any child elements, only values
@Marsharks and @Ryan Berger: Do note that this outputs strange results when there is some PI before root element...
yes, I saw that. Mine is an InfoPath form. My solution works for me.
1

This is probably the shortest solution :) :

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

Comments

1

This stylesheet:

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

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

Comments

0

you helped get me close enough

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.