Pretty Print XML in Javascript

25. January 2013 12:20 by Mrojas in   //  Tags: , , ,   //   Comments (0)

I searched all over for a simple solution to pretty print xml with JavaScript. I saw several answers in StackOverflow, but I just wanted a straight answer that I could just paste on my page and voila! but no. I couldn't find one.

Some people suggested using Google Prettify and is fine but prettify does not handle indentation and I had to escape the < > characters in my xml, and I just wanted to embed the xml in the page and have javascript handle the rest.

For the indentation some people recommended another javascript called vkBeautify but I just wanted a quick snipped of how to do it, well in the end my friend Joseph and I just put together a quick sample.

It was very simple but I tought there should be a lot of people with something like that already done.


We embed our xml like this:

<script type="text/xml" id="xml2">


Indentation is handled with the vkBeautity.

var text = textToHtml(vkbeautify.xml(document.getElementById('xml2').innerHTML));

Then we needed a function to do the escaping for us:

var pr_amp = /&/g;
var pr_lt = /</g;
var pr_gt = />/g;
var pr_quot = /\"/g;
/** escapest html special characters to html. */
function textToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>');

And the rest is just using the google prettify:

<body onload="updateText(),prettyPrint()" bgcolor="white">
<pre class="prettyprint" id="xml">

NOTE: this solution still has a problem with carriage returns. So indentation is yet to be fixed

 UPDATE: I have fixed the issue. For some reason the IE gets rid of the '\n' in the string. So your have to change them for a <BR>

function updateText() {
	   		var text = textToHtml(vkbeautify.xml(document.getElementById('xml2').innerHTML));
			var expr = new RegExp("\n","g")


For IE you might need to add this after the doctype:

<!doctype html>
 <meta http-equiv="X-UA-Compatible" content="IE=Edge"> (26.35 kb) (27.49 kb)

Save msbuild output to XML files

3. February 2012 23:09 by Mrojas in   //  Tags: , ,   //   Comments (0)

Today my friend Allan was asking me if I know of a way to save msbuild output as an XML file. His idea was to be able to process compilation errors without depending on tools like grep / sed. I really had never done that so I ask him to send me a link if he found something.

Well he found

He tested it and he says it works great. So if you ever need something like that take a look at it.