Skip to content

Instantly share code, notes, and snippets.

@js1972
Created September 5, 2013 04:54
Show Gist options
  • Save js1972/6446246 to your computer and use it in GitHub Desktop.
Save js1972/6446246 to your computer and use it in GitHub Desktop.
#JavaScript formatXML will format an xml string with line feeds (pretty printer)
/*
Format a XML string - pretty printer (with line feeds)
*/
function formatXml(xml) {
var formatted = '';
var reg = /(>)(<)(\/*)/g;
xml = xml.replace(reg, '$1\r\n$2$3');
var pad = 0;
jQuery.each(xml.split('\r\n'), function(index, node) {
var indent = 0;
if (node.match( /.+<\/\w[^>]*>$/ )) {
indent = 0;
} else if (node.match( /^<\/\w/ )) {
if (pad != 0) {
pad -= 1;
}
} else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) {
indent = 1;
} else {
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}
formatted += padding + node + '\r\n';
pad += indent;
});
return formatted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment