4

I'm new to CF, coming from a .NET background. I'm wondering what the best practice type thing would be for the following situation.

Say I have a component, car.cfc and I have a function inside this component that requires the properties:

<cfcomponent>
    <cfproperty name="Name" />
    <cfproperty name="Model" />
    <cfproperty name="Make" />

    <cffunction name="BuildCarXML">
        <cfargument name="car" type="car" />
        <cfsavecontent variable="xmlCar">
            <?xml version="1.0" encoding="UTF-8" ?>
            <car>
               <name>#arguments.car.Name#</name>
            </car>
        </cfsavecontent>
        <cfreturn xmlCar />
    </cffunction>
</cfcomponent>

Finally, i call this function from a cfm page:

<cfscript>
    cfcCar = CreateObject("car");
    cfcCar.Name="AU";
</cfscript>
<cfdump var="#cfcCar.BuildCarXML(cfcCar)#">

My question is, is this the correct/best way to do this?

mnsr
  • 12,337
  • 4
  • 53
  • 79

1 Answers1

1
<cfcomponent accessor="true">
    <cfproperty name="name" />
    <cfproperty name="model" />
    <cfproperty name="make" />

    <cffunction name="BuildCarXML" output="false">
        <cfsavecontent variable="local.xmlCar">
            <cfoutput><?xml version="1.0" encoding="UTF-8" ?>
            <car>
               <name>#variables.name#</name>
            </car></cfoutput>
        </cfsavecontent>
        <cfreturn xmlCar />
    </cffunction>
</cfcomponent>

Finally, u call this function from a cfm page:

<cfscript>
    cfcCar = new Car();
    cfcCar.setName("AU");
    writeDump(cfcCar.BuildCarXML());
</cfscript>
Henry
  • 32,689
  • 19
  • 120
  • 221
  • You may look into using `` if you want to also validate the xml u're building is really valid xml. – Henry Feb 07 '14 at 01:39
  • I was using cfxml, and i'm about to open another question about it vs savecontent. – mnsr Feb 07 '14 at 01:42
  • well, with `` and `toString()` you're constructing an xml object in CF. So it'd be easier if you want to do `xmlsearch()` later, or manipulate it through the API. However, your current `` way would be faster, but watch out for unexpected whitespaces, especially in the beginning that may break some xml parser. – Henry Feb 07 '14 at 01:44
  • I'm trying to build an xml file, but it's split into multiple functions. see my question: http://stackoverflow.com/questions/21617998/cfxml-vs-cfsavecontent-unable-to-build-xml-using-cfxml Thanks – mnsr Feb 07 '14 at 02:12