Skip to content

Instantly share code, notes, and snippets.

@joedf
Forked from kurtsson/formatXML.js
Last active January 22, 2021 00:00
Show Gist options
  • Save joedf/3a54061a2f11ea912ed807db56dd114f to your computer and use it in GitHub Desktop.
Save joedf/3a54061a2f11ea912ed807db56dd114f to your computer and use it in GitHub Desktop.
formatXML.js (without jQuery, supports XML empty tags, optionally escape for HTML)
/* pretty-print / beautify XML strings
* Released under the MIT License (MIT)
* Copyright (c) 2021 Joe DF
*
* Modified from (Martin Kurtsson):
* https://gist.github.com/kurtsson/3f1c8efc0ccd549c9e31
*
* which is based on (Stuart Powers):
* https://gist.github.com/sente/1083506
*/
function formatXml(xml, padChar = '\t', escapeHTML = false, useEmptyTags = true) {
var formatted = '', prevLine = '', newLine = '\r\n', pad = 0;
var reg = /(>)(<)(\/*)/g;
xml = xml.toString().replace(reg, '$1'+newLine+'$2$3');
var nodes = xml.split(newLine);
for (var n in nodes) {
var node = nodes[n];
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 += padChar;
}
var currLine = node + newLine;
if (prevLine.trim().replace('<', '</') == node.trim()) {
formatted = formatted.slice(0, 0 - newLine.length - 1);
if (useEmptyTags)
formatted += '/>' + newLine;
else
formatted += '>' + currLine;
} else {
formatted += padding + currLine;
}
pad += indent;
prevLine = currLine;
}
if (escapeHTML)
return formatted.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;');
return formatted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment