6

I am using the following call to obtain the XML code for part of my DOM.

var sXML = new XMLSerializer().serializeToString(document.getElementsByTagName("TopElementTag")[0]);

However, when I display this string, it is all one line.

Is there a way to format this string so that it has line breaks and tabs to make it easily humanly readable?

2 Answers 2

8

I used vkBeutify with the following code.

var sXML = new XMLSerializer().serializeToString(document.getElementsByTagName("TopElementTag")[0]);
sXML = vkbeautify.xml(sXML);
2

This mini-library can prettify and minify in less than 1kb uncompressed.

https://gist.github.com/max-pub/a5c15b7831bbfaba7ad13acefc3d0781

https://codepen.io/maxpub/pen/qBWPJEL?editors=1010

XML = {
    parse: (string, type = 'text/xml') => new DOMParser().parseFromString(string, type),  // like JSON.parse
    stringify: DOM => new XMLSerializer().serializeToString(DOM),                         // like JSON.stringify

    transform: (xml, xsl) => {
        let proc = new XSLTProcessor();
        proc.importStylesheet(typeof xsl == 'string' ? XML.parse(xsl) : xsl);
        let output = proc.transformToFragment(typeof xml == 'string' ? XML.parse(xml) : xml, document);
        return typeof xml == 'string' ? XML.stringify(output) : output; // if source was string then stringify response, else return object
    },

    minify: node => XML.toString(node, false),
    prettify: node => XML.toString(node, true),
    toString: (node, pretty, level = 0, singleton = false) => { 
        if (typeof node == 'string') node = XML.parse(node);
        let tabs = pretty ? Array(level + 1).fill('').join('\t') : '';
        let newLine = pretty ? '\n' : '';
        if (node.nodeType == 3) return (singleton ? '' : tabs) + node.textContent.trim() + (singleton ? '' : newLine)
        if (!node.tagName) return XML.toString(node.firstChild, pretty);
        let output = tabs + `<${node.tagName}`; // >\n
        for (let i = 0; i < node.attributes.length; i++)
            output += ` ${node.attributes[i].name}="${node.attributes[i].value}"`;
        if (node.childNodes.length == 0) return output + ' />' + newLine;
        else output += '>';
        let onlyOneTextChild = ((node.childNodes.length == 1) && (node.childNodes[0].nodeType == 3));
        if (!onlyOneTextChild) output += newLine;
        for (let i = 0; i < node.childNodes.length; i++)
            output += XML.toString(node.childNodes[i], pretty, level + 1, onlyOneTextChild);
        return output + (onlyOneTextChild ? '' : tabs) + `</${node.tagName}>` + newLine;
    }
}



1
  • Works great, thanks - only issue was when calling prettify on an xml document with a stylesheet node it bombed - so I just deleted that node with doc.removeChild(doc.firstChild). Aug 29, 2021 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.