Wednesday, April 22, 2009

How to output XML file to HTML In Coldfusion

<!--- Answers to be stored in an array --->
<cfset hotspots=ArrayNew(1)>
<!--- XML string is a Valid XML --->
<!--- Parse XML into a Struct --->
<cfset xml_struct=XMLParse(xml_string)>
<!--- use cfdump to understand the xml_struct and modify the loop below to suit --->
<cfloop from="1" to="#ArrayLen(XMLRoot.Hotspot)#" index="i">
<cfset hotspot=StructNew()>
<cfloop list="Name,X,Y" index="attrib">
<cfif IStructKeyExists(XMLRoot.Hotspot[i].XMLAttributes,attrib)>
<cfset StructInsert(hotspot,attrib,XMLRoot.Hotspot[i].XMLAttributes[attrib],true)>
<cfset StructInsert(hotspot,attrib,iif(attrib eq "Name",'""','"0"'),true)>
<cfset ArrayAppend(hotspots,hotspot)>
<!--- find the 1st case of <hotspot[^>]*> --->
<cfset hotspot_find=ReFindNoCase(xml_string,"<hotspot[^>]*>",1,true)>
<!--- Loop while hotspot_find is successful --->
<cfloop condition="#hotspot_find.len[1]#">
<!--- create a structure to hold the answers --->
<cfset hotspot=StructNew()>
<--- extract the individual <hotspot> element --->
<cfset hotspot_data=mid(xml_string,hotspot_find.pos[1],hotspot_find.len[1])>
<!--- loop for the required attributes --->
<cfloop list="name,x,y" index="attrib">
<!--- search for the attributes --->
<cfset attrib_find=ReFindNoCase(hotspot_data,'#Attrib#="[^"]*"',1,true)>
<cfif ArrayLen(attrib_find.len) eq 2 and attrib_find.len[1]>
<!--- Attribute exists and has value --->
<cfset structInsert(hotspot,attrib,mid(hotspot_data,attrib_find.pos[1],attrib_find.len[1]),true)>
<!--- Attribute doesn't exist or has no value --->
<cfset structInsert(hotspot,attrib,iif(attrib eq "name",'""','"0"'),true>
<!--- Append the struct hotspot to the array hotspots --->
<cfset ArrayAppend(hotspots,hotspot)>
<!--- Locate the next <hotspot> element --->
<cfset hotspot_find=ReFindNoCase(xml_string,"<hotspot[^>]*>",hotspot_find.pos[1]+hotspot_find.len[1],true)>
<cfdump var="#hotspots#">

No comments: