How can I save an MSXML2.DomDocument with indenting? (I think it uses MXXMLWriter)

Cheeso picture Cheeso · Jun 21, 2012 · Viewed 9.9k times · Source

I have an instance of MSXML2.DomDocument.

I wave to save it, with indenting.

This code works, but does not indent:

var dom = new ActiveXObject("MSXML2.DomDocument");
// fiddle with dom here
dom.save(filename);

I think I can use an MXXMLWriter object to inject indenting.

How?

Answer

Cheeso picture Cheeso · Jun 21, 2012

This oughta do it.

function saveDomWithIndent(dom, filename) {
    var writer =  new ActiveXObject("MSXML2.MXXMLWriter"),
        reader = new ActiveXObject("MSXML2.SAXXMLReader"),
        fso = new ActiveXObject("Scripting.FileSystemObject"),
        textStream = fso.CreateTextFile(filename, true);
    writer.indent = true;
    writer.omitXMLDeclaration = true;
    reader.contentHandler = writer;
    reader.parse(dom);
    textStream.Write(writer.output);
    textStream.Close();
}

Use it like this:

var root, node, newnode, 
    dom = new ActiveXObject("MSXML2.DOMDocument.6.0");
dom.async = false;
dom.resolveExternals = false;
dom.load(fullpath);
root = dom.documentElement;
node = root.selectSingleNode("/root/node1");
if (node !== null) {
    newnode = dom.createElement('node2');
    newnode.text = "hello";
    root.appendChild(newnode);
    saveDomWithIndent(dom, fullpath);
}

I could not figure out how to adjust the indent level. It always indents with a tab.