How do I return XML from a CFC that can be used with Spry?

There are a few things to look out for when returning XML to Spry. Make sure you set output=false for both the component and the method to suppress any whitespace that may be included with the returned XML. Also note the <cfcontent> tag directly before returning the XML. This is not needed for returning XML to other consumers such as Flex, but without it, Spry will not recognize it as valid XML. Special thanks to Bruce Phillips for pointing this out. Below is a sample components with 1 method that returns XML that can be consumed by Spry.

<cfcomponent name="Baseball" output="false">
	
	<cffunction name="getTeams" access="remote" returntype="xml" 
output="false">
		<cfset var teams = "" />
		<cfset var tmp = "" />
		<cfset var xmlObj = "" />
		
		<!---
			Create a new query object and populate 5 rows with data.  In most cases
			your application will be retrieving data from a database via 
<cfquery> tag.
		--->
		<cfset teams = queryNew("Team, Mascot", "varchar, varchar") />		
		<cfset tmp = queryAddRow(teams, 5) />		
		<cfset tmp = querySetCell(teams, "Team", "Boston", 1) />
		<cfset tmp = querySetCell(teams, "Mascot", "Red Sox", 1) />
		<cfset tmp = querySetCell(teams, "Team", "New York", 2) />
		<cfset tmp = querySetCell(teams, "Mascot", "Yankees", 2) />
		<cfset tmp = querySetCell(teams, "Team", "Baltimore", 3) />
		<cfset tmp = querySetCell(teams, "Mascot", "Orioles", 3) />
		<cfset tmp = querySetCell(teams, "Team", "Toronto", 4) />
		<cfset tmp = querySetCell(teams, "Mascot", "Blue Jays", 4) />
		<cfset tmp = querySetCell(teams, "Team", "Tampa Bay", 5) />
		<cfset tmp = querySetCell(teams, "Mascot", "Devil Rays", 5) />
		
		<!---
			Loop through the query and create XML formatted text, which we will 
then convert
			to an XML document object.  You could also use Ray Camden's toxml.cfc 
component to accomplish this.
		--->
		<cfset xmlObj = "<baseball>" />		
		<cfoutput query="teams">		
			<cfset xmlObj = xmlObj & "<teams>" />				
			<cfset xmlObj = xmlObj & "<team>" />
			<cfset xmlObj = xmlObj & "#team#" />
			<cfset xmlObj = xmlObj & "</team>" />
			<cfset xmlObj = xmlObj & "<mascot>" />
			<cfset xmlObj = xmlObj & "#mascot#" />
			<cfset xmlObj = xmlObj & "</mascot>" />
			<cfset xmlObj = xmlObj & "</teams>" />
		</cfoutput>		
		<cfset xmlObj = xmlObj & "</baseball>" />
		
		<!---
			Convert the XML formatted text to an XML document object.
		--->
		<cfset xmlObj = xmlParse(xmlObj) />
		
		<!---
			Spry will not recognize the returned XML without this line.  Thanks 
to Bruce Phillips (www.brucephillips.name)
			for this tip.
		--->
		<cfcontent type="application/xml; charset=UTF-8">
						
		<cfreturn xmlObj />		
		
	</cffunction>
	
</cfcomponent>

This question was written by Steve Milburn
It was last updated on March 5, 2007.

Categories

XML

Comments

comments powered by Disqus