Copying Children From One ColdFusion XML Document To Another

Posted May 14, 2007 at 8:37 AM

Tags: ColdFusion

The other day, Matthew Abbott had contacted me to ask about some advanced JDOM libraries. I have not used JDOM directly in any way so I couldn't really help him. But this got me thinking about XML in general but more specifically, about XML in ColdFusion. I just don't use it that often and certainly, I don't do anything cool with it. So, I thought I would take this opportunity to try some cool stuff.

For this experimentation, I have created two XML document objects: xmlDate and xmlGirls. The xmlDate XML document outlines the agenda for a hot date (who doesn't love pizza and a movie???). The xmlGirls XML document is an XML database of girls:

 Launch code in new window » Download code as text file »

  • <!---
  • Build our XML data object to outline the activities
  • of our date. Right now, we only have information about
  • the girl by way of her foriegn key ID.
  • --->
  • <cfxml variable="xmlDate">
  •  
  • <date>
  • <girl id="4" />
  • <meal>
  • <location>Ben's Pizza</location>
  • <time>7:30 PM</time>
  • </meal>
  • <movie>
  • <name>Friends With Money</name>
  • <time>9:15 PM</time>
  • </movie>
  • </date>
  •  
  • </cfxml>
  •  
  •  
  • <!---
  • Here is our XML data object that holds the more detailed
  • information about our girls. We can use the IDs here to
  • populate foreign references to these girls.
  • --->
  • <cfxml variable="xmlGirls">
  •  
  • <girls>
  • <girl id="1">
  • <name>Kit Cat</name>
  • <hair>Brunette</hair>
  • <eyes>Blue</eyes>
  • </girl>
  • <girl id="4">
  • <name>Anna Banana</name>
  • <hair>Brunette</hair>
  • <eyes>Brown</eyes>
  • </girl>
  • <girl id="5">
  • <name>Marcie Darcey</name>
  • <hair>Blonde</hair>
  • <eyes>Brown</eyes>
  • </girl>
  • </girls>
  •  
  • </cfxml>
  •  
  •  
  • <!--- Dump out our date. --->
  • <cfdump
  • var="#xmlDate#"
  • label="xmlDate XML Data"
  • />
  •  
  • <!--- Dump out our girls. --->
  • <cfdump
  • var="#xmlGirls#"
  • label="xmlGirls XML Data"
  • />

CFDumping out the xmlDate XML document, we get:


 
 
 

 
ColdFusion XML Document Object Model For xmlDate  
 
 
 

CFDumping out the xmlGirls XML document, we get:


 
 
 

 
 
 
 
 

Now, our XML document about the date has the girl's ID, but that doesn't really help us out much. What we want to do is copy the properties of the girl from the xmlGirls document to the Girl node of the xmlDate document. My first thought about this was, no problem, just use the AddAll() method for the child nodes collection:

 Launch code in new window » Download code as text file »

  • <!---
  • Add the girl properties to the girl node
  • of our date XML docuemnt.
  • --->
  • <cfset xmlDate.Date.Girl.XmlChildren.AddAll(
  • xmlGirls.Girl[ 2 ].XmlChildren
  • ) />

The problem is that when you run the above code, you get the following ColdFusion error:

WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.

The issue, which I had never thought about, was that each Node of an XML document is owned by that document. You can't just use a single XML node in two different places and especially NOT in two different XML documents (just as I can't be both at work and at the movies at the same time!!!).

So, how do we get around this? We have to import the girl node into our xmlDate document before we try and insert it somewhere into our xmlDate XML document object model. To help accomplish this, I have come up with a ColdFusion user defined function, XmlAppend(). This UDF takes two XML nodes from two different XML documents (one from each) and then appends the child nodes of the latter to the child nodes of the former:

 Launch code in new window » Download code as text file »

  • <cffunction
  • name="XmlAppend"
  • access="public"
  • returntype="any"
  • output="false"
  • hint="Copies the children of one node to the node of another document.">
  •  
  • <!--- Define arguments. --->
  • <cfargument
  • name="NodeA"
  • type="any"
  • required="true"
  • hint="The node whose children will be added to."
  • />
  •  
  • <cfargument
  • name="NodeB"
  • type="any"
  • required="true"
  • hint="The node whose children will be copied to another document."
  • />
  •  
  •  
  • <!--- Set up local scope. --->
  • <cfset var LOCAL = StructNew() />
  •  
  • <!---
  • Get the child nodes of the originating XML node.
  • This will return both tag nodes and text nodes.
  • We only want the tag nodes.
  • --->
  • <cfset LOCAL.ChildNodes = ARGUMENTS.NodeB.GetChildNodes() />
  •  
  •  
  • <!--- Loop over child nodes. --->
  • <cfloop
  • index="LOCAL.ChildIndex"
  • from="1"
  • to="#LOCAL.ChildNodes.GetLength()#"
  • step="1">
  •  
  •  
  • <!---
  • Get a short hand to the current node. Remember
  • that the child nodes NodeList starts with
  • index zero. Therefore, we must subtract one
  • from out child node index.
  • --->
  • <cfset LOCAL.ChildNode = LOCAL.ChildNodes.Item(
  • JavaCast(
  • "int",
  • (LOCAL.ChildIndex - 1)
  • )
  • ) />
  •  
  • <!---
  • Import this noded into the target XML doc. If we
  • do not do this first, then COldFusion will throw
  • an error about us using nodes that are owned by
  • another document. Importing will return a reference
  • to the newly created xml node. The TRUE argument
  • defines this import as DEEP copy.
  • --->
  • <cfset LOCAL.ChildNode = ARGUMENTS.NodeA.GetOwnerDocument().ImportNode(
  • LOCAL.ChildNode,
  • JavaCast( "boolean", true )
  • ) />
  •  
  • <!---
  • Append the imported xml node to the child nodes
  • of the target node.
  • --->
  • <cfset ARGUMENTS.NodeA.AppendChild(
  • LOCAL.ChildNode
  • ) />
  •  
  • </cfloop>
  •  
  •  
  • <!--- Return the target node. --->
  • <cfreturn ARGUMENTS.NodeA />
  • </cffunction>

Once we have this nifty ColdFusion XML UDF, we can easily copy the girl properties from the xmlGirls document to the xmlDate document:

 Launch code in new window » Download code as text file »

  • <!---
  • Get the ID of the girl we are going to be taking
  • out on the date. We want to get more information
  • about her in our date data object.
  • --->
  • <cfset intDateID = xmlDate.Date.Girl.XmlAttributes.ID />
  •  
  • <!---
  • Search for the matching girl in our girl xml data
  • object. When searching with XPath, search for a
  • girl with the given ID. All we need is the ID since
  • each girl has a unique ID.
  • --->
  • <cfset arrGirls = XmlSearch(
  • xmlGirls,
  • "//girl[@id=#intDateID#]"
  • ) />
  •  
  •  
  • <!---
  • Check to see if we found a matching girl in our
  • girl date object.
  • --->
  • <cfif ArrayLen( arrGirls )>
  •  
  • <!---
  • Our XPath search above has returned a matching
  • girl. Now, we want to append those returned girl's
  • properties child nodes) to the girl node of our
  • Date data object.
  • --->
  • <cfset XmlAppend(
  • xmlDate.date.girl,
  • arrGirls[ 1 ]
  • ) />
  •  
  • </cfif>
  •  
  •  
  • <!--- Dump out the resultant XML date document. --->
  • <cfdump
  • var="#XmlDate#"
  • label="xmlDate After Girl Node Import"
  • />

Once the node is copied, our resultant xmlDate XML document looks like this:


 
 
 

 
ColdFusion XML Document Object Model For xmlDate After XmlAppend()  
 
 
 

The girl properties of Girl ID 4 copies over quite nicely. This is some very interesting stuff. It gives me all sorts of ideas about building xml documents in pieces and then easily joining them together to make a bigger, better document (like denormalizing a database).

Download Code Snippet ZIP File

Comments (12)  |  Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page




Adobe ColdFusion 8.0.1 Update - Helping Programmers To Be Signifanctly Less Girlie - Download ColdFusion 8 Update 8.0.1 Now.

Reader Comments

Wow! This is a pretty impressive technique.

Do you know where documentation exists that talks about these built-in functions within the XML document object? I've only ever been familiar with the functions in the CF documentation, which aren't nearly this powerful.

Thanks in advance,
Toby

Posted by Toby Reiter on May 14, 2007 at 9:50 AM


@Toby,

Take a look at this:

http://java.sun.com/j2se/1.4.2/docs/api/org/w3c/dom/Node.html

It covers the w3c.org java DOM stuff. It seems that ColdFusion is wrapping around that functionality.

Posted by Ben Nadel on May 14, 2007 at 9:54 AM


Rock on! Thanks for the link!

Posted by Toby Reiter on May 14, 2007 at 10:03 AM


On a recent project, I had the need to copy one node to another 'parent' node. I just used duplicate() on the node and it worked fine.

I was told by a co-worker that it would not work because every XML node has a 'parentNode'. Apparently in CFMX 7, Cf is smart enough to remove that reference when you duplicate(). I am not certain how this would work if I tried to move it to a completely different XML document.

Posted by Scott Stroz on May 14, 2007 at 10:28 AM


Ben,

Check out this XMLMerge UDF I created back in February which uses XSLT to merge.

http://www.intersuite.com/client/index.cfm/2007/2/15/XMLMerge-UDF-Uses-XSLT-to-merge-root-child-nodes

Regards,

Chris

Posted by Christopher Wigginton on May 14, 2007 at 10:37 AM


@Chris,

That looks pretty cool. I know nothing about XSLT (I have tried to learn it but I just can't seem to get a handle on its seemly irregular programming syntax). I like what you are doing; my only issue with it is that you have to re-parse XML, which might have a lot of over head.

Cool stuff though. I really should learn more about XSLT.

Posted by Ben Nadel on May 14, 2007 at 11:04 AM


Working with XML in Coldfusion is painful and slow. There are much better Java library options available. My blog entry details the problems and a solution using XOM and a StAX processor:

http://orangepips.instantspot.com/blog/index.cfm/2007/3/28/XML-StAX-Processing-with-Coldfusion

Posted by Matthew Lesko on May 14, 2007 at 12:57 PM


@Matt,

That is some interesting stuff. I have not done anything with XML outside of the core ColdFusion installed libraries. I will have to take a look at that other stuff sometime.

Posted by Ben Nadel on May 14, 2007 at 5:46 PM


Just wanted to say thanks for writing this comment! I ran into this same issue while doing some XML work today, and this saved me a TON of headache. Thanks!

Posted by Jonathon Stierman on Oct 1, 2007 at 8:11 PM


Hey ben this is great and it almost solved my problem. Im trying to import a specific child to another xml document in the same parent. I tried to tweak your function to accept a new argument for a specific child but it doesnt seem to be working. Some of these functions are new to me.

Posted by Aaron Wallrich on Feb 4, 2008 at 11:19 PM


Thanks, this worked great for me.

Posted by Larry on Mar 6, 2008 at 2:37 PM


This worked great for manipulating a Word 2003 XML document. I'm using it to insert the contents of one document into another.

Posted by Matthew Fox on Jul 4, 2008 at 5:28 PM


Post Comment  |  Ask Ben


Home   |   Web Log   |   ColdFusion   |   Projects   |   Resume   |   Job Form   |   Search   |   Contact
Epicenter Consulting - Custom Software Solutions for Business Evolution HostMySite.com - The Leader In ColdFusion Hosting