Posts Tagged ‘XML’

Beautify XML String in JavaScript

Posted: September 28, 2015 by Sagar Wasule in JavaScript
Tags: ,

Ok so here is a scenario where for requirement I had to properly indent the string xml viz, beautify the xml string with proper indentation.

function formatXml(xml) {

var formatted = '';
var reg = /(>)\s*(<)(\/*)/g;
xml = xml.replace(/\r|\n/g, ''); //deleting already existing whitespaces
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(/.+]*>$/)) {
indent = 0;
} else if (node.match(/^<\/\w/)) {
if (pad != 0) {
pad -= 1;
}
} else if (node.match(/^]*[^\/]>.*$/)) {
indent = 1;
} else {
indent = 0;
}

var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}

formatted += padding + node + '\r\n';
pad += indent;
});

return formatted;
}


This article explains parsing XML file using XmlDocument  and XDocument  in C#.

(more…)