Reputation: 29206
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?
Upvotes: 0
Views: 100
Reputation: 62929
This should work and also pretty-print the output:
using(var writer =
XmlWriter.Create(filename, new XmlWriterSettings { Indent = true }))
{
document.Save(writer);
}
Upvotes: 1
Reputation: 96750
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);
}
Upvotes: 1
Reputation: 15501
You need to work with XmlDocument.CreateNode(XmlNodeType, string, string) overload by specifying XmlNodeType.XmlDeclaration
. This should add a declaration node to the document.
Upvotes: 1