Skip to content

Instantly share code, notes, and snippets.

@minhd
Created September 3, 2012 05:07
Show Gist options
  • Save minhd/3606837 to your computer and use it in GitHub Desktop.
Save minhd/3606837 to your computer and use it in GitHub Desktop.
formatXML with indentation
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