xmlcharacter-encodingcoldfusioncoldfusion-11

How can I set the encoding of an XML document in ColdFusion?


I am creating and XML object using <cfxml>:

<cfxml variable="LOCAL.Xml">
    <Root>
        <Header>
            <CompanyName>ACME</CompanyName>
            <AccountNumber>ACM1234</AccountNumber>
            <FileTimeStamp>2020-05-19{T}22:13:51</FileTimeStamp>
            <TimeZone>EDT</TimeZone>
        </Header>
    </Root>
</cfxml>

When I convert it to a String, the XML declaration is added to the top with encoding="UTF-8". How do I specify a different encoding using CF11?

I've tried <cfprocessingdirective encoding="iso-8859-1">.

I've tried <cfheader name="content-disposition" charset="iso-8859-1" value="attachment; filename=file.xml" />.

I've tried converting it to Binary with encoding "iso-8859-1" and then back to string.

Every time I get the same result.


Solution

  • This is copied from the documentation for cfxml posted here - CFXML

    To convert an XML document object back into a string, use the ToString function, at which time ColdFusion automatically prepends the <?xml version="1.0" encoding="UTF-8" ?> XML declaration.

    To change the declaration to specify another encoding, use the Replace function. To specify the encoding of the text that is returned to a browser or other application, use the cfcontent tag. The following example illustrates this process:

    <cfprocessingdirective suppressWhiteSpace = "yes">
    <cfcontent type="text/xml; charset=utf-16">
    <cfxml variable="xmlobject">
        <breakfast_menu>
        <food>
            <name quantity="50">Belgian Waffles</name>
            <description>Our famous Belgian Waffles</description>
        </food>
        </breakfast_menu>
    </cfxml>
    
    <!--- <cfdump var="#xmlobject#">--->
    
    <cfset myvar=toString(xmlobject)>
    <cfset mynewvar=replace(myvar, "UTF-8", "utf-16")>
    
    <!---<cfdump var="#mynewvar#">--->
    
    <cfoutput>#mynewvar#</cfoutput>
    </cfprocessingdirective>
    

    The cfprocessingdirective tag prevents ColdFusion from putting white space characters in front of the XML declaration.

    Notice the mention that "ColdFusion automatically prepends the <?xml version="1.0" encoding="UTF-8" ?> XML declaration"

    And their recommended method to change that using "the Replace function". So for you the replace would become:

    <cfset myvar=toString(xmlobject)>
    <cfset mynewvar=replace(myvar, "UTF-8", "iso-8859-1")>
    

    And you would also want to change the cfcontent tag as:

    <cfcontent type="text/xml; charset=iso-8859-1">