Here is my xml file or xml object.
<boarders>
<boarder>
<name>Joe</name>
<board>Forum</board>
<gender>M</gender>
</boarder>
</boarders>
I want to add another boarder.
Here I am reading from a file but the same thing works for an xml object.
<cfset xml = xmlParse("boarders.xml")/>
I create my new boarder node, using the variable xml as my "xml document".
<cfset boarder = XmlElemNew(xml,"boarder")/>
Next I create some extra nodes "name,gender, and board" and append it to the boarder node using arrayAppend(). Each time I make the "extra nodes" I set the value of the node by using XmlText, which is an attribute of xml object in ColdFusion. Finally we add the node the children of the boarder node created earlier.
<!---name--->
<cfset name = XmlElemNew(xml,"name")/>
<cfset name.XmlText = "Jamie"/>
<cfset arrayAppend(boarder.XmlChildren,name)/>
<!---gender--->
<cfset gender = xmlElemNew(xml,"gender")/>
<cfset gender.XmlText = "F"/>
<cfset arrayAppend(boarder.XmlChildren,gender)/>
<!---board--->
<cfset board = xmlElemNew(xml,"board")/>
<cfset board.XmlText = "Nitro"/>
<cfset arrayAppend(boarder.XmlChildren,board)/>
Once we are ready to add the node the xml object we just arrayAppend() just like we did with the above nodes "name,gender,and board".
<cfset arrayAppend(xml.boarders.XmlChildren,boarder)>
<cfdump var="#xml#">
<cfabort/>
That's it.
To recap quick:
1. Create the node using XmlElemNew().
2. Set the node value using XmlText().(optional)
3. Append the node to the parent node using arrayAppend().
Took me forever to figure it out. Sad I know.
Thanks for the post. At least it saved someone time :)
ReplyDelete