tags:

views:

31

answers:

3

In my code:

XmlDocument document = new XmlDocument();
XmlElement book = document.CreateElement("book");
document.AppendChild(book);

... // create and add a bunch of nodes

document.Save(filename);

I want to modify my code so that the string <?xml version="1.0"?> is saved at the top of filename. What is the simplest way to do this?

+1  A: 

You need to work with XmlDocument.CreateNode(XmlNodeType, string, string) overload by specifying XmlNodeType.XmlDeclaration. This should add a declaration node to the document.

Appu
+1  A: 

Without manipulating the document, you can provide the Save method with an XmlWriter, which writes the XML declaration by default:

    using (XmlWriter xw = XmlWriter.Create(filename))
    {
        document.Save(xw);
    }
Robert Rossney
This works, but for some reason now my document prints all on one line (instead of pretty printing). It's not that big a deal, but it would help with debugging for it to pretty print. Any idea why?
Matthew
+1  A: 

This should work and also pretty-print the output:

using(var writer =
  XmlWriter.Create(filename, new XmlWriterSettings { Indent = true }))
{
  document.Save(writer);
}
Ray Burns
Yep, this does it. Thanks!
Matthew