Skip to content

Instantly share code, notes, and snippets.

@edwinm
Created October 14, 2022 08:35
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 edwinm/ee1a4aec5c0a15741a8affcb56805e39 to your computer and use it in GitHub Desktop.
Save edwinm/ee1a4aec5c0a15741a8affcb56805e39 to your computer and use it in GitHub Desktop.
Pretty Print XML
prettyXml(xml: string) {
try {
const domParser = new DOMParser();
const xmlDom = domParser.parseFromString(xml, 'application/xml');
const xsltDom = domParser.parseFromString(
`<xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform>
<xsl:strip-space elements="*"/>
<xsl:template match="para[content-style][not(text())]">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:output indent="yes"/>
</xsl:stylesheet>`,
'application/xml',
);
const xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDom);
const resultDoc = xsltProcessor.transformToDocument(xmlDom);
xml = new XMLSerializer().serializeToString(resultDoc);
} catch (e) {}
return xml;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment