Scott Hanselman blogs about a GotDotNet user sample that allows you to strip document declaration


However, one of the comments to the posted solution comes up with what may be an even more elegant solution that does not rely on reflection:

"Rather than use reflection and change the internal state of the writer, you could also write something to the XmlTextWriter instance. "

Here is s "short but complete" (a la Jon Skeet) example I whipped up:

using System;
using System.Xml;
using System.Xml.Serialization ;
using System.IO;
namespace XmlserializerFaker
public class SerializationHelper
public static string ToXml( Object o )
XmlSerializer serializer =
new XmlSerializer( o.GetType() );
StringWriter stringWriter =
new StringWriter();
// Create an instance of an xml text writer, with no formatting.
// Then write something (actually nothing) to the writer
// in order to set the internal state to something other than the
// start state, which omits the xml declaration.
XmlTextWriter xmlWriter = new XmlTextWriter( stringWriter );
xmlWriter.Formatting = Formatting.None;
xmlWriter.WriteRaw( "" );
// Faking the existence of custom namespaces has a nice side effect
// of leaving namespaces out entirely.
XmlSerializerNamespaces faker = new XmlSerializerNamespaces();
faker.Add( "",
null );
serializer.Serialize( xmlWriter, o, faker );
return stringWriter.ToString();
public class EngineState
private string _name;
public string Name
get{ return _name;}
public EngineState(){}
public EngineState(string name)

this.Name =name;
class ShowMe
static void Main(string[] args)
EngineState st =
new EngineState("Ted");
string x= SerializationHelper.ToXml(st);
Console.WriteLine (x);

This kind of trick can be especially useful to serialize a class that represents a state or configuration, and just save it as more or less a "config" file.