code
window.formatXML = function (xml, tab) {
var formatted = '', indent = '';
tab = tab || ' ';
xml.split(/>\s*</).forEach(function (node) {
if (node.match(/^\/\w/)) indent = indent.substring(tab.length);
formatted += indent + '<' + node + '>\r\n';
if (node.match(/^<?\w[^>]*[^\/]$/)) indent += tab;
});
return formatted.substring(1, formatted.length - 3);
}
input
<?xml version="1.0" encoding="UTF-8"?>
<animals class="object">
<dog class="array"><e class="object"><age type="number">15</age>
<name type="string">Rufus</name></e>
<e class="object">
<age class="object" null="true"/>
<name type="string">Marty</name>
</e></dog></animals>
output
如果需要对XML、HTML的尖括号转义可以看这个文章:https://blog.csdn.net/qq_38132283/article/details/106568132