Created
May 6, 2021 09:19
-
-
Save chzager/ac5b2156cf8345b1120bcf79f74af965 to your computer and use it in GitHub Desktop.
Pretty Print XML
This file contains hidden or 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
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