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">
<data><test>10</test><test>20</test></data>
</script>

 

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">
</pre>
</body>
 

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")
	   		document.getElementById('xml').innerHTML=text.replace(expr,'<br>');
		}

 UPDATE2:

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

<!doctype html>
 <meta http-equiv="X-UA-Compatible" content="IE=Edge">

prettyxml.zip (26.35 kb)

prettyxml2.zip (27.49 kb)

Categories