Created
September 5, 2013 04:54
-
-
Save js1972/6446246 to your computer and use it in GitHub Desktop.
#JavaScript formatXML will format an xml string with line feeds (pretty printer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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