How do I control the generation of XML processing instructions during serialization?

XML processing instructions include the little bits at the top of an XML document that are meant to describe how the XML document is to be handled. These processing instructions are a way to pass information to the parser that is outside the scope of the prescribed structure of the document. However, it is not uncommon to want to suppress processing instructions. For example, many applications that perform text manipulation on the XML document deal poorly with this extra information. A particular stumbling block is the XML declaration at the start of the document since that is the most common processing instruction that an XML generator might provide by default.

When using an XmlSerializer, you can disable the XML declaration by providing a customized XML writer to the serializer. The serializer takes an instance of the writer when calling the Serialize method. The writer takes an instance of XmlWriterSettings when the writer is created. And finally, the writer settings include a setting controlling the generation of the XML declaration.

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlWriter writer = XmlWriter.Create(output, settings);
serializer.Serialize(writer, data);

Next time: Serializing Object Graphs