With browsers being as generous as they are about whitespace, ColdFusion, like every other scripting language I have used, doesn’t seem to make much of an effort to keep it to a minimum. Typically, whitespace is not a concern since browsers handle it so well, however if you are trying to generate an XML document, it can be a big problem. That’s why we have tags like cfsilent, cfprocessingdirective, and cfsetting, and that’s why we have the ability to enable whitespace management in the ColdFusion administrator. However, CFMX for J2EE doesn’t seem to come with the whitespace management option, and sometimes no matter what combination of whitespace management tags I use, I simply cannot prevent the server from writing out a few carriage returns at the top of the document (which makes for invalid XML). I finally discovered the ultimate solution.
The best way I have found to prevent whitespace is to manage the buffer and the output stream yourself. When a page is being executed, generated content is being written to a buffer, and that buffer gets flushed to the output stream which represents the connection between your server and a browser. You can use the cfflush tag to flush that buffer if you need data to reach the client faster (for instance, if you want to give them feedback about a process which might take several seconds to complete), and you can also clear that buffer as well, which means you can get rid of unwanted whitespace! The only way I have found to do it is to resort to Java. The following does the trick:
The most bullet proof way I have found for generating valid XML in ColdFusion is to use a combination of the cfsavecontent tag and the Java code above, like this:
<cfset someVar = "Whitespace can be a pain."/><cfsavecontent variable="responseXml"><?xml version="1.0"?><root><element><cfoutput>#someVar#</cfoutput></element></root></cfsavecontent><cfscript>getPageContext().getOut().clearBuffer();writeOutput(responseXml);</cfscript>
Feel free to share your whitespace techniques here. I’m interested in knowing how others solve this problem.