views:

634

answers:

4

What's the best way to pretty-print xml in JavaScript? I obtain xml content through ajax call and before displaying this request in textarea i want to format it so it looks nice to the eye :)

A: 

Actually, whitespace matters in XML. So how would you define "pretty"?

Arjan
By pretty i mean properly idented and one tag per line.
mgamer
You answer is incorrect IMHO. The RFC makes clear that there is a notion of insignificant whitespace e.g. that may be added for enhanced readability. It is for this reason tyhat the xml:space attribute exists; to allow the author to specify where their whitespace is definitely significant
Rob Levine
oops - meant to add url: http://www.w3.org/TR/REC-xml/#sec-white-space
Rob Levine
Correct. So, without an XSD (or DTD), all whitespace matters, right? Of course, in real life, whitespace that is not part of the content is most often insignificant (and parsers tend to be forgiving). I've seen a lot of actual data being changed for "readability" though. And thanks to Murphy, often not until some system was taken into production. ;-)
Arjan
+1  A: 

This is not the best way to do this but you can get the xml as text and use RegExp to find and replace '>' with tabs according to the depth of the node and breaklines but I don't really know RegExp very well, sorry.

You can also use XSLT and transform it using javascript.
Check this link and take a look at this tutorial.

the_drow
The links are good, especially the first, "Pretty XML tree view for Opera" (though in my Safari and Firefox the clicking to collapse or expand elements does not work out of the box).
Arjan
+2  A: 

This does not take care of any indenting, but helps to encode the XML for use within <pre> or <textarea> tags:

/* hack to encode HTML entities */
var d = document.createElement('div'); 
var t = document.createTextNode(myXml); 
d.appendChild(t);
document.write('<pre>' + d.innerHTML + '</pre>');

And if, instead of a <textarea>, you'd want highlighting and the nodes to be collapsable/expandable, then see Displaying XML in Chrome Browser on Super User.

Arjan
+1  A: 

I agree with Arjan on utilizing the <pre> tags. I was trying to decipher 'ugly' xml code in my html output before I tried this out about 2 days ago. Makes life much easier and keeps you sane.

Knix
+1 to get you some reputation to allow you to comment...
Arjan
thanks =) it's tough to get going here
Knix
Well, I'm not sure we couldn't have lived *without* the answer even if it were a comment, but well... Deleting it now may also purge the upvote, so wait until you've got at least 60 reputation then. :-)
Arjan