Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active January 24, 2023 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamoCA/f4db70dd266b6640f4e6adc302d062db to your computer and use it in GitHub Desktop.
Save JamoCA/f4db70dd266b6640f4e6adc302d062db to your computer and use it in GitHub Desktop.
Adobe ColdFusion UDF to convert valid XML (string or object) to a pretty-print XML string. (Doesn't work with Lucee CFML.)
<cfscript>
// borrowed from https://gist.github.com/aviflax/725761/5887c83a695cd0d7a9be70c9c41c08e59c6611a6
// 2023-01-24 Rewritten in cfscript; Updated to use isxml/isxmldoc; Works w/CF10+, but not Lucee CFML.
// Tweet: https://twitter.com/gamesover/status/1617969485855752192
string function prettyXml(required any xml) hint="I convert valid XML (string or object) to a pretty-print XML string" {
if (isxml(arguments.xml)){
local.xmlstring = createobject("java", "java.io.StringReader").init(javacast("string", arguments.xml));
local.document = createobject("java", "org.jdom.input.SAXBuilder").init().build(local.xmlstring);
} else if (isxmldoc(arguments.xml)){
local.document = createobject("java", "org.jdom.input.DOMBuilder").init().build(arguments.xml);
} else return "";
local.format = createobject("java", "org.jdom.output.Format").getPrettyFormat();
local.out = createobject("java", "org.jdom.output.XMLOutputter").init(local.format);
return local.out.outputString(local.document);
}
</cfscript>
<cfinclude template="./pretty-print-xml.cfm">
<cfsavecontent variable="myXml">
<note><to>Tove</to><from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body></note>
</cfsavecontent>
<cfoutput>
<h1>ColdFusion #server.coldfusion.productVersion#</h1>
<h2>Before</h2>
<pre>#encodeforhtml(trim(myXml))#</pre>
<h2>Ater</h2>
<pre>#encodeforhtml(prettyXml(myXml))#</pre>
</cfoutput>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment