Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 10:30
Show Gist options
  • Save bennadel/9758860 to your computer and use it in GitHub Desktop.
Save bennadel/9758860 to your computer and use it in GitHub Desktop.
Changing The Root Node In A ColdFusion XML Document Using XSLT
<!---
Create an XML string that has a root node that gets
repeated within the body of the XML as well.
--->
<cfsavecontent variable="strXmlData">
<list id="my-to-do-list">
<item>
List Item A
</item>
<item>
List Item B
</item>
<item>
<list>
<item>
Sub Item A
</item>
<item>
Sub Item B
</item>
</list>
</item>
<item>
List Item D
</item>
</list>
</cfsavecontent>
<!--- Define XSLT to repace the root node. --->
<cfsavecontent variable="strXSLData">
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--- Define new root node name BELOW. --->
<xsl:variable name="new-root-node">
<xsl:text>masterlist</xsl:text>
</xsl:variable>
<!--- Define new root node name ABOVE. --->
<!--- --------------------------------------------- --->
<!--- Match the root node. --->
<xsl:template match="/*">
<!--- Create a new element with new node name. --->
<xsl:element name="{$new-root-node}">
<!---
Copy all attributes of the existing root
node into the new root node.
--->
<xsl:for-each select="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="." />
</xsl:attribute>
</xsl:for-each>
<!--- Copy all children of the root node. --->
<xsl:copy-of select="*" />
</xsl:element>
</xsl:template>
</xsl:transform>
</cfsavecontent>
<!--- Transform the XML. --->
<cfset xmlNew = XmlTransform(
Trim( strXmlData ),
Trim( strXSLData )
) />
<!--- Output new XML document with new root node. --->
<cfdump
var="#XmlParse( xmlNew )#"
label="New XML Root"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment