User Guide

Table Of Contents
Modifying a ColdFusion XML object 863
Adding an element
You can add an element by creating a new element or by using an existing element.
Use the
XmlElemNew function to create a new, empty element. This function has the following
form:
XmlElemNew(docObject, elementName)
where docObject is the name of the XML document object in which you are creating the element,
and elementName is the name you are giving the new element.
Use an assignment statement with an existing element on the right side to create a new element
using an existing element. See “Copying an existing element” on page 864 for more information
on adding elements using existing elements.
Adding an element using a function
You can use the ArrayInsertAt or ArrayAppend functions to add an element to an XML
document object. For example, the following line adds a phoneNumber element after the last
element for employee.name[2]:
<cfset ArrayAppend(mydoc.employee.name[2].XmlChildren, XmlElemNew(mydoc,
"phoneNumber"))>
The following line adds a new department element as the first element in employee. The name
elements become the second and third elements.
<cfset ArrayInsertAt(mydoc.employee.XmlChildren, 1, XmlElemNew(mydoc,
"department"))>
You must use the format parentElement.XmlChildren to specify the array of elements to which
you are adding the new element. For example, the following line causes an error:
<cfset ArrayInsertAt(mydoc.employee.name, 2, XmlElemNew(mydoc, "PhoneNumber")>
If you have multiple child elements with the same name, and you want to insert a new element in
a specific position, use the
XmlChildPos function to determine the location in the XmlChildren
array where you want to insert the new element. For example, the following code determines the
location of mydoc.employee.name[1] and inserts a new name element as the second name
element:
<cfscript>
nameIndex = XmlChildPos(mydoc.employee, "name", 1);
ArrayInsertAt(mydoc.employee.XmlChildren, nameIndex + 1, XmlElemNew(mydoc,
"name"));
</cfscript>
Using a namespace
When you use a function to add an element, you can assign the element to
a namespace by including the namespace prefix in the element name. If you have not yet
associated the prefix with a namespace URI, you must also include a parameter with the
namespace URI in the
XmlElemNew function. This parameter must be the second parameter in the
method, and the element name must be the third parameter. ColdFusion MX then associates the
namespace prefix with the URI, and you can omit the URI parameter in further
xmlElemNew
functions.