Reputation: 682
I need to convert XML created by our ColdFusion backend into a specifically formatted Javascript variable for use in the JQWidgets tree (see http://www.jqwidgets.com/community/topic/xml-tree-with-empty-nodes/#post-7215 for background information).
What is the easiest way to iterate through the XML and create the javascript appropriately? Due to the complexity of my XML, I don't think that the ColdFusion ToScript will work, but I'm more than willing to use it.
Example XML data:
<Role>
<RoleID>16</RoleID>
<RoleName>Role C</RoleName>
<Certifications>
<Certification>
<CertificationID>45</CertificationID>
<CertificationName>Certification 2</CertificationName>
<Requirements>
<Requirement>
<RequirementID>678</RequirementID>
<RequirementName>Requirement A</Requirement>
</Requirement>
</Requirements>
</Certification>
</Certifications>
</Role>
<Role>
<RoleID>16</RoleID>
<RoleName>Role D</RoleName>
<Certifications>
<Certification>
<CertificationID/>
<CertificationName/>
</Certification>
</Certifications>
</Role>
</Roles>
Example Javascript variable:
var source = [
{ label: "Role C", expanded: true, items: [
{ label: "Certification 2", items: [
{ label: "Requirement A" }
]},
]},
{ icon: "", label: "Role D" }
];
Upvotes: 2
Views: 367
Reputation: 1951
If you don't want to reinvent the wheel, you could use the Xml2Struct project to parse the xml into a struct, then use SerializeJson() to get a Javascript object.
Example:
<cfsavecontent variable="myXml">
<Roles>
<Role>
<RoleID>16</RoleID>
<RoleName>Role C</RoleName>
<Certifications>
<Certification>
<CertificationID>45</CertificationID>
<CertificationName>Certification 2</CertificationName>
<Requirements>
<Requirement>
<RequirementID>678</RequirementID>
<RequirementName>Requirement A</RequirementName>
</Requirement>
</Requirements>
</Certification>
</Certifications>
</Role>
<Role>
<RoleID>16</RoleID>
<RoleName>Role D</RoleName>
<Certifications>
<Certification>
<CertificationID/>
<CertificationName/>
</Certification>
</Certifications>
</Role>
</Roles>
</cfsavecontent>
<cfinvoke component="xml2Struct" method="ConvertXmlToStruct" xmlNode="#myXml#" str="#{}#" returnVariable="result">
<cfdump var="#serializeJson(result)#">
Even if you don't want to use the project, you can view the source for a good example of how to parse xml.
Upvotes: 2