Skip to content

Instantly share code, notes, and snippets.

@Suppenhuhn79
Created May 6, 2021 09:19
Show Gist options
  • Save Suppenhuhn79/ac5b2156cf8345b1120bcf79f74af965 to your computer and use it in GitHub Desktop.
Save Suppenhuhn79/ac5b2156cf8345b1120bcf79f74af965 to your computer and use it in GitHub Desktop.
Pretty Print XML
prettyPrintXml = function (xmlString)
{
/* linearize */
let result = xmlString.replace(/>\s*</g, "><").trim();
/* simplify empty tags */
result = result.replace(/<(\S+)([^>]*)><\/\1>/g, "<$1$2/>");
/* remove spaces at tag end */
result = result.replace(/\s+(\/?>)/g, "$1");
/* remove too many spaces before attributes */
result = result.replace(/\s+(\s\S+="\S+")/g, "$1");
/* split each tag in a single line */
result = result.replace(/></g, ">\n<");
let xmlLines = result.split("\n");
result = "";
let indent = 0;
for (let line of xmlLines)
{
if (line.startsWith("</"))
{
indent -= 1;
};
result += " ".repeat(Math.max(indent, 0)) + line + "\r\n";
if ((line.startsWith("</") === false) && ((line.endsWith("/>") === false)))
{
indent += 1;
};
};
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment