User Guide

Table Of Contents
862 Chapter 35: Using XML and WDDX
Adding, deleting, and modifying XML elements
The following sections describe the basic techniques for adding, deleting, and modifying XML
elements. The example code uses the XML document described in “A simple XML document
on page 845.
Counting and finding the position of child elements
Often, an XML element has several children with the same name. For example, in the XML
document defined in the simple XML document, the employee root element has multiple name
elements.
To manipulate such an object, you often need to know the number of children of the same name,
and you might need to know the position in the
XmlChildren array of a specific child name that
is used for multiple children. The following sections describe how to get this information.
Counting child elements
The following user-defined function determines the number of child elements with a specific
name in an element:
<cfscript>
function NodeCount (xmlElement, nodeName)
{
nodesFound = 0;
for (i = 1; i LTE ArrayLen(xmlElement.XmlChildren); i = i+1)
{
if (xmlElement.XmlChildren[i].XmlName IS nodeName)
nodesFound = nodesFound + 1;
}
return nodesFound;
}
</cfscript>
The following lines use this function to display the number of nodes named “name” in the
mydoc.employee element:
<cfoutput>
Nodes Found: #NodeCount(mydoc.employee, "name")#
</cfoutput>
Determining the position of a child element with a common name
The XmlChildPos function determines the location in the XmlChildren array of a specific
element with a common name. You use this index when you need to tell ColdFusion where to
insert or delete child elements. For example, if there are several name elements in
mydoc.employee, use the following code to locate name[2] in the
XmlChildren array:
<cfset nameIndex = XmlChildPos(mydoc.employee, "name", 2)>