Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Forked from eduardolundgren/gist:4149429
Created November 26, 2012 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/4149524 to your computer and use it in GitHub Desktop.
Save jonathantneal/4149524 to your computer and use it in GitHub Desktop.
XMLFormatter from Kaleo Designer
var STR_CHAR_CRLF = '\r\n';
var STR_BLANK = '';
var STR_CHAR_TAB = '\t';
var repeat = function(str, length) {
return new Array(length + 1).join(str);
};
var XMLUtil = {
REGEX_TOKEN_1: /(>)\s*(<)(\/*)/g,
REGEX_TOKEN_2: /.+<\/\w[^>]*>$/,
REGEX_TOKEN_3: /^<\/\w/,
REGEX_TOKEN_4: /^<\w[^>]*[^\/]>.*$/,
format: function(xml) {
var instance = this;
var i;
var pad = 0;
var formatted = STR_BLANK;
var lines = xml.replace(instance.REGEX_TOKEN_1, '$1' + STR_CHAR_CRLF + '$2$3').split(/\r?\n/g);
lines.forEach(
function(item, index, collection) {
var indent = 0;
if (item.match(instance.REGEX_TOKEN_2)) {
indent = 0;
}
else if (item.match(instance.REGEX_TOKEN_3)) {
if (pad !== 0) {
pad -= 1;
}
}
else if (item.match(instance.REGEX_TOKEN_4)) {
indent = 1;
}
formatted += repeat(STR_CHAR_TAB, pad) + item + STR_CHAR_CRLF;
pad += indent;
}
);
return formatted.replace(/^\s+|\s+$/g, "");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment