Matthew
Matthew

Reputation: 29206

What is the simplest way to save basic processing instructions with my XmlDocument in C#?

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

Answers (3)

Ray Burns
Ray Burns

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

Robert Rossney
Robert Rossney

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

Navaneeth K N
Navaneeth K N

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

Related Questions