Nov 04

Make your XML look pretty

Posted by James Netherton | Tuesday 04 November 2008 4:52 PM | In ColdFusion,Java

Credit goes to Joe Rinehart for most of this from this post.

ColdFusion ships with JDom which gives you full access to the JDom API. Many of the applications I work with have some kind of XML component to them and sometimes the XML is difficult to read if it's not formatted nicely.

I've used Joe's code example to create a simple interface on top of it. It also works with valid XHTML.

<cfparam name="form.submit" default=""/>
<cfparam name="form.xml" default=""/>
<cfscript>
function prettyXML(xmlString){

   var fileObj = "";
   var builder = "";
   var format = "";
   var out = "";
   var document = "";
   var fileInStream = "";
   var fileOutStream = "";
   var filePath = expandPath("./prettyXML.xml");

   try{
      fileWrite(filePath, arguments.xmlString);

      fileObj = createObject("java", "java.io.File").init(filePath) ;
      builder = createObject("java", "org.jdom.input.SAXBuilder").init() ;
      format = createObject("java", "org.jdom.output.Format").getPrettyFormat() ;

      format.setIndent("   ");
      out = createObject("java", "org.jdom.output.XMLOutputter").init(format);
      fileInStream = createObject("java", "java.io.FileInputStream").init(fileObj );

      document = builder.build(fileInStream);

      fileInStream.close();

      fileDelete(filePath);

      return out.outputString(document);
   }
   catch(Any excpt){
      if(isDefined("fileInStream") and fileInStream neq ""){
         fileInStream.close();
      }

      writeOutput("<p>#excpt.message#</p>");
      writeOutput("<p>#excpt.stacktrace#</p>");
   }
}
</cfscript>
<html>
<head>
<title>Paste your ugly XML</title>
<style type="text/css">
   body, input{
      font-family:Trebuchet MS;
   }
</style>
</head>
<body>
<h3>Input your XML:</h3>
<cfoutput>
<form action="#cgi.SCRIPT_NAME#" method="post">
<p><textarea name="xml" rows="20" cols="100">#form.xml#</textarea></p>
<input name="submit" type="submit" value="Go"/>
</form>
<h3>Pretty XML</h3>
<cfif len(form.submit) and len(form.xml)>#htmlCodeFormat(prettyXML(form.xml))#</cfif>
</cfoutput>
</body>
</html>

 

0 Comments

[Post comment]


Leave a comment








Captcha text