Created
November 26, 2012 17:12
-
-
Save eduardolundgren/4149429 to your computer and use it in GitHub Desktop.
XMLFormatter from Kaleo Designer
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
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: /(>)(<)(\/*)/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; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment