1
votes

I want to modify an XLM document using the Microsoft/XMLDOM object. The output should place each element on a new line and the indent level should match the nesting level. I tried this with a script like this:

 var objXML = new ActiveXObject("Microsoft.XMLDOM");
 objXML.load("in.xml")
 var CRLF = objXML.createTextNode("\n");
 var root = objXML.documentElement;

 var node = objXML.createNode(1, "A", root.namespaceURI);
 var text = objXML.createTextNode("foo");
 node.appendChild(text);
 root.appendChild(node);
 root.appendChild(CRLF);  // creates NOT a newline after <A>foo</A>

 node = objXML.createNode(1, "B", root.namespaceURI);
 text = objXML.createTextNode("bar");
 node.appendChild(text);
 root.appendChild(node);
 root.appendChild(CRLF);  // creates a newline after <B>bar</B>

 objXML.save("out.xml");

With this input file "in.xml"

<root>
</root>

This results in

<root>
    <A>foo</A><B>bar</B>
</root>

I know that the XML output is valid and can be read by other applications like Internet Explorers or any other program that uses XMLDOM, libXML, or something similar. But for asthetic reasons and probably to simplify manual editing I would like to get a well-formatted output.

How can I change the script to get this result?

<root>
  <A>foo</A>
  <B>bar</B>
</root>

I added the appendChild(CRLF) at some places. But it doesn't work between the added elements.

1

1 Answers

0
votes

Indentation and formatting of XML documents is not be done using XML markup and content. Xml focuses on a way to represent data for software systems. Many XML-aware applications will handle the representation of Xml, by way of indentation and other formatting, themselves (e.g. a web browser). Again, you do not need to tell IE where to put a new line and where to indent, because it understands XML, by putting any specific content in XML itself (e.g. CRLF). If you still prefer to do it the way you have chosen to, beware that XML parsers and toolkits will treat any such content as XML and process accordingly.