Monday, June 1, 2009

Adding new data to XML using Coldfusion

Recently asked a Question 

"Need to create an XML file in which data is appended to existing XML"

Answer is pretty simple, first create  XML using cfxml tag

<cfprocessingdirective suppresswhitespace="Yes">
<cfxml variable="xmlobject">
<data>
        <name>Brijesh Chauhan</name>
        <email>abc@gmail.com</email>
        <name>Radhika Chauhan</name>
        <email>def@gmail.com</email>
</data>
</cfxml>

Then insert New XML nodes using array insert, we will always insert the new data at first and second position(as in this case there are two children's).

<cfscript>
ArrayInsertAt(xmlobject.data.XmlChildren, 1, XmlElemNew(xmlobject,"name"));
ArrayInsertAt(xmlobject.data.XmlChildren, 2, XmlElemNew(xmlobject,"email"));
</cfscript>

Finally assign new data to the childrens

<cfset xmlobject.data.XmlChildren[1].XmlText = "Avyukth Chauhan"> 
<cfset xmlobject.data.XmlChildren[2].XmlText = "ghi@gmail.com"> 
</cfprocessingdirective > 

Simple !!!!

No comments: