Search code examples
xmlxsltroot-node

Copy XML file contents except for root node and attribute XSLT


I am working on a small XSLT file to copy the contents of an XML file and strip out the declaration and root node. The root node has an namespace attribute.

I currently have it working except for now the namespace attribute is now being copied to the direct children nodes.

Here is my xslt file so far, nothing big or complicated:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

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

My input file is like this:

<?xml version="1.0" encoding="UTF-8"?>
<Report_Data xmlns="examplenamespace">
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
</Report_Data>

The output after the XSLT is like this:

<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>
<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>
<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>

The problem is, every Report_Entry tag is now getting that xml namespace attribute from the root node that I removed.

In case you were wondering, I know the output of the XSLT is not well formed. I am adding the XML declaration and a different root node name later on after the XSLT trasnformation.


Solution

  • The following produces the output that you want:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8"/>
    
      <!-- For each element, create a new element with the same local-name (no namespace) -->
      <xsl:template match="*">
        <xsl:element name="{local-name()}">
          <xsl:copy-of select="@*"/> 
          <xsl:apply-templates/>
        </xsl:element>
      </xsl:template>
    
      <!-- Skip the root element, just process its children. -->
      <xsl:template match="/*">
        <xsl:apply-templates/>
      </xsl:template>
    
    </xsl:stylesheet>