XML parsing in Coldfusion has improved a lot in the last few versions but converting a complex XML object to a Coldfusion structure is still a struggle I beleive. There are a few custom tags out there for doing this but the ones that I have used or know are all only for simple structures, not nested or subnested structures. So I use this little function I and one of my other friends worked on and it works like a charm.

Update (27/12/2008) : The new code has been upload on riaforge and the usage is now very simple . It now takes the XML file and converts to Struct without doing all the Xpath’s before the function call. Here is a sample usage.

<cffile action="read" file="#ExpandPath('books.xml')#" variable="myBooks">
<cfdump var = "#ConvertXmlToStruct(ToString(myBooks), structnew())#">

The new code is here as well – Xml2Struct CFC

Anything below is now outdated :-

Update : Project can now be downloaded from here

A sample usage of the fucntion is below :-

Read the XML file into a Coldfusion variable, this can be a from a file locally or via a CFHTTP call or a webservice call.

<cffile action="read" file="#ExpandPath('books.xml')#" variable="myBooks">
<cfset myXml = XmlParse(myBooks) />
You need to know the root element of the XML document and pass that to the function.
<cfset xmlBody= xmlSearch(myXml,"//catalog") />

Then call the function to convert it to a Structure.

<cfdump var = "#ConvertXmlToStruct(responseBody[1], structnew())#">

The function itself can be found here.

The only problem that I notice about this is if the root element has any default namespaces (“xmlns=’blabla’) , the XmlSearch doesnt recognise it. Apart from that, it works like a charm.

The XML file used in this sample can be found here books sample xml file .

Screen Dump of OutputHere is the output of the code.