CFXML: Probing XMLDOM in ColdFusion - How do we get to the attributes?
(Page 4 of 5 )
You dig a little deeper to get the attributes, which are also represented as a structure in ColdFusion as follows. Here I am trying to locate the attribute of the first child of the root element.
<cffile action="read" file="C:\Inetpub\wwwroot\webstudents.xml"
variable="xmldoc">
<cfset mydoc = XmlParse(xmldoc)>
<cfset rootchild1=#mydoc.xmlroot.xmlchildren[1].XMLAttributes#>
<cfdump var="#rootchild1#">
The display for the above snippet will come out as shown below:

It is also possible to navigate through the document using the element names as shown in the following example.
<cffile action="read" file="C:\Inetpub\wwwroot\webstudents.xml"
variable="xmldoc">
<cfset mydoc = XmlParse(xmldoc)>
<cfset childs=#mydoc.XMLRoot.student.XMLChildren#>
<cfdump var="#childs#">
The result shows that it picks the first student node it finds as shown below.

Can we home in on a named node?
If you look at the above picture you will see that individual items for the student node can be picked out as shown below.
<cfset mydoc = XmlParse(xmldoc)>
<cfset childsChild1=#mydoc.XMLRoot.student.XMLChildren[1].XMLName#>
<cfoutput>
mydoc.XMLRoot.student.XMLChildren[1].XMLName=
#childsChild1#
</cfoutput>
<br/>
<cfset childsChild2=#mydoc.XMLRoot.student.XMLChildren[2].XMLName#>
<cfoutput>
mydoc.XMLRoot.student.XMLChildren[2].XMLName=
#childsChild2#
</cfoutput>
<br/>
<cfset childsChild1t=#mydoc.XMLRoot.student.XMLChildren[1].XMLText#>
<cfoutput>
mydoc.XMLRoot.student.XMLChildren[1].XMLText=
#childsChild1t#
</cfoutput>
<br/>
<cfset childsChild2t=#mydoc.XMLRoot.student.XMLChildren[2].XMLText#>
<cfoutput>
mydoc.XMLRoot.student.XMLChildren[2].XMLText=
#childsChild2t#
</cfoutput>
The above code will display the following on the browser.

How can we then access the individual students? Well, it is an extension of the same idea. We have to closely follow the Macromedia documentation to delineate the details as shown below for the second child of the root element. With more than one way to access, and with syntaxes that are quite different, it can be quite confusing, although it adds to flexibility.
<cffile action="read" file="C:\Inetpub\wwwroot\webstudents.xml"
variable="xmldoc">
<cfset mydoc = XmlParse(xmldoc)>
<cfset rootchild2=#mydoc.xmlroot.xmlchildren[2]#>
<cfdump var="#rootchild2#">
This will show the structure of the second student node as shown below.

Next: How do we get at the Comment node? >>
More ColdFusion Articles
More By Jayaram Krishnaswamy