JS XML pretty print using XSLT
Example for an SO question: https://stackoverflow.com/questions/376373/pretty-printing-xml-with-javascript
by Artur Klesun
HTML
<body>
<div>Pretty XML output follows...</div>
<textarea class="output-holder" rows="15" cols = "60"></textarea>
</body>
JavaScript
var prettifyXml = function(sourceXml)
{
var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
var xsltDoc = new DOMParser().parseFromString([
// describes how we want to modify the XML - indent everything
'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
' <xsl:strip-space elements="*"/>',
' <xsl:template match="para[content-style][not(text())]">', // change to just text() to strip space in text nodes
' <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>',
].join('\n'), 'application/xml');
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
var resultDoc = xsltProcessor.transformToDocument(xmlDoc);
var resultXml = new XMLSerializer().serializeToString(resultDoc);
return resultXml;
};
var prettyXml = prettifyXml([
'<root><node/>',
' <Sale price="100.00">',
' <segment> 0 LO4394L 14SEP PHXORD GK1</segment>',
' <segment> 1 LO 999L 14SEP PHXORD GK1</segment>',
' <segment> 2 LO 789L 15SEP WAWODS GK1</segment>',
' <segment> 12 LO4394T 14SEP PHXORD GK1</segment>',
' <name>Vasya Pupkin</name></Sale>',
'</root>',
].join('\n'));
document.querySelector('.output-holder').value = prettyXml;