Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print pretty xml in javascript?

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 :)

like image 668
mgamer Avatar asked Dec 03 '22 07:12

mgamer


2 Answers

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.

like image 101
Arjan Avatar answered Dec 04 '22 20:12

Arjan


take a look at the vkBeautify.js plugin

http://www.eslinstructor.net/vkbeautify/

it is exactly what you need. it's written in plain javascript, less then 1.5K minified and very fast: takes less then 5 msec. to process 50K XML text.

like image 43
vadimk Avatar answered Dec 04 '22 20:12

vadimk