Cook Computing

Use XmlWriter to Create XML without Encoding Attribute

January 18, 2009 Written by Charles Cook

I am currently modifiying XML-RPC.NET to support Silverlight 2. One problem I encountered is that when you use XmlWriter.Create to create an XML writer on top of a stream it is not possible pass a null encoding to specify that you don't want an encoding attribute in the XML declaration at the start of the document.

By default a StreamWriter created on top of the stream will result in an encoding of "utf-8". For example this program:

class Program
{
  static void Main(string[] args)
  {
    FileStream stm = new FileStream(@"c:\temp\test.xml",
        FileMode.OpenOrCreate | FileMode.Truncate);
    WriteXml(stm);
  }

  static void WriteXml(Stream stm)
  {
    var stmWriter = new StreamWriter(stm);
    var settings = new XmlWriterSettings();
    var xmlWriter = XmlWriter.Create(stmWriter, settings);
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteElementString("foo", "bar");
    xmlWriter.Close();
  }
}

Creates this document:


<?xml version="1.0" encoding="utf-8"?><foo>bar</foo>

If you try to specify a null encoding:

    StreamWriter stmWriter = new StreamWriter(stm, null);

An instance of ArgumentNullException is thrown. A solution is to derive a class from StreamWriter and override the Encoding property:

public class EncodingStreamWriter : StreamWriter
{
  Encoding _encoding;

  public EncodingStreamWriter(Stream stm, Encoding encoding)
    : base(stm)
  {
    _encoding = encoding;
  }

  public override Encoding Encoding
  {
    get { return _encoding; }
  }
}

And then use this instead of StreamWriter:

    var stmWriter = new EncodingStreamWriter(stm, null);

To create the desired XML document:

<?xml version="1.0"?><foo>bar</foo>