Listing 1: TextMethod.cfm
<!--- Querying and moving data from a database
to XML - the Text method --->

<cfquery name="qEmps" datasource="CFSnippets">
select * from Employees
</cfquery>

<cfxml variable="xmlDoc">
<Employees>
<cfoutput query="qEmps">
<Employee ID="#qEmps.Emp_ID#">
<FirstName>#qEmps.FirstName#</FirstName>
<LastName>#qEmps.LastName#</LastName>
<Email>#qEmps.Email#</Email>
</Employee>
</cfoutput>
</Employees>
</cfxml>

<cfdump var="#xmlDoc#">
<cffile action="WRITE"
file="#ExpandPath('.')#\employees.xml" 
output="#toString(xmlDoc)#">

Listing 2: Employees.xml
<?xml version="1.0" encoding="UTF-8"?>
<Employees>

<Employee ID="1">
<FirstName>Carolynn</FirstName>
<LastName>Peterson</LastName>
<Email>CPETERSON</Email>
</Employee>

<Employee ID="2">
<FirstName>Dave</FirstName>
<LastName>Heartsdale</LastName>
<Email>FHEARTSDALE</Email>
</Employee>

<Employee ID="3">
<FirstName>Linda</FirstName>
<LastName>Stewart</LastName>
<Email>LSTEWART</Email>
</Employee>

... more Employee elements ...

</Employees>

Listing 3: ObjectMethod.cfm
<!--- Querying and moving data from a database
to XML - the Object method --->

<cfquery name="qEmps" datasource="CFSnippets">
select * from Employees
</cfquery>

<!--- Create a new XML document --->
<cfset xmlDoc=XMLNew()>
<cfset xmlDoc.XMLRoot=
xmlElemNew(xmlDoc, "Employees")>
<cfset root=xmlDoc.XMLRoot>

<cfloop query="qEmps">
<!--- Create a new element and get a reference to it --->
<cfset ArrayAppend(root.xmlChildren,
xmlElemNew(xmlDoc, "Employee") )>
<cfset emp=root.xmlChildren[
ArrayLen(root.xmlChildren)]>

<!--- Set an attribute --->
<cfset emp.xmlAttributes.ID = qEmps.Emp_ID>

<!--- Add child elements and populate with data --->
<cfset ArrayAppend(emp.xmlChildren,
xmlElemNew(xmlDoc, "FirstName"))>
<cfset emp.FirstName.xmlText=qEmps.FirstName>
<cfset ArrayAppend(emp.xmlChildren,
xmlElemNew(xmlDoc, "LastName"))>
<cfset emp.LastName.xmlText=qEmps.LastName>
<cfset ArrayAppend(emp.xmlChildren,
xmlElemNew(xmlDoc, "Email"))>
<cfset emp.Email.xmlText=qEmps.Email>
</cfloop>

<!--- Include the utilities file --->
<cfinclude template="xmlUtilities.cfm"> 
<!--- Output the resulting XML to the browser --->
<cfcontent type="text/xml">
<cfoutput>#XMLIndent(xmlDoc)#</cfoutput>

Listing 4: xmlUtilities.cfm
<!--- xmlUtilities.cfm - functions to
help with XML processing --->

<!--- XMLIndent()
requires one argument of type XML
returns the resulting XML as text --->
<cffunction name="XMLIndent" returntype="string">
<cfargument name="xml" type="any" required="Yes">

<cfset xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>'>
<cfset output=xmltransform(
tostring(arguments.xml), variables.xsl)>
<cfreturn output>

</cffunction>