Home > Mobile >  XSLT - make everything below the root element a children of a new element
XSLT - make everything below the root element a children of a new element

Time:09-07

Any ideas on how this can be achieved please. So regardless of the xml structure, I want to create a new element below the root, and make everything below the root in the source xml a child of this new element.

Regards

Steve

CodePudding user response:

It does depend on exactly what you mean, and how you want to handle namespaces and attributes, but I suspect it's something like

<xsl:template match="/*">
  <xsl:copy>
    <new-element>
      <xsl:copy-of select="."/>
    </new-element>
  </xsl:copy>
</xsl:template>

CodePudding user response:

This should work with stylesheet parameters where you indicate if you want to keep the root element's attributes in the root element. Also, you pass in the name of the new child element. Probably some extra work required for adding a namespaced child element.

<?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" indent="yes" />
  
  <xsl:param name="keepRootAttributes" select="false()" />
  <xsl:param name="newElementName"     select="'new_child'" />

  <xsl:template match="/*">

    <xsl:copy>
      <xsl:if test="$keepRootAttributes">
        <xsl:copy-of select="@*" />
      </xsl:if>
      <xsl:element name="{$newElementName}">
        <xsl:if test="not($keepRootAttributes)" >
          <xsl:copy-of select="@*" />
        </xsl:if>
        <xsl:copy-of select="node()" />
      </xsl:element>
    </xsl:copy>

  </xsl:template>

</xsl:stylesheet>
  • Related