Pretty-printing formatted XML in ColdFusion via JDOM
Posted by Joe Rinehart at 12:49 PM
7 comments - Categories:
ColdFusion MX
Over the weekend I was working on parts of MG3 that generate some XML. When I used ColdFusion's toString(xmlDocument) to print back out the application's main ModelGlue.xml file, I completely forgot that doing so strips it of all comments and formatting. Yikes!
I dug around for a bit and found that the JDOM library shipped with ColdFusion provides a utility for pretty-printing XML, and wrapped it up in the following UDF:
<cfargument name="filename" type="string" hint="Filename of XML document to pretty-print." />
<cfargument name="destination" type="string" hint="Filename for output." default="#arguments.filename#" />
<cfset var fileObj = "" />
<cfset var builder = "" />
<cfset var format = "" />
<cfset var out = "" />
<cfset var document = "" />
<cfset var fileInStream = "" />
<cfset var fileOutStream = "" />
<cfset fileObj = createObject("java", "java.io.File").init(filename) />
<cfset builder = createObject("java", "org.jdom.input.SAXBuilder").init() />
<cfset format = createObject("java", "org.jdom.output.Format").getPrettyFormat() />
<!--- Use tabs instead of two spaces --->
<cfset format.setIndent(" ") />
<cfset out = createObject("java", "org.jdom.output.XMLOutputter").init(format) />
<cfset fileInStream = createObject("java", "java.io.FileInputStream").init(fileObj) />
<cfset document = builder.build(fileInStream) />
<cfset fileInStream.close() />
<cfset fileObj = createObject("java", "java.io.File").init(destination) />
<cfset fileOutStream = createObject("java", "java.io.FileOutputStream").init(fileObj) />
<cfset out.output(document, fileOutStream) />
<cfset fileOutStream.close() />
</cffunction>
Below is an example of its input and output:
Input
Output
<!-- Ugly XML -->
<root>
<child attrib="value" />
</root>
John Allen wrote on 04/07/08 1:26 PM
Ohhhhhhhh I wish i had that code 4 months ago.That is SLICK.