How to put an encoding attribute to xml other that utf-16 with XmlWriter?

You need to use a StringWriter with the appropriate encoding. Unfortunately StringWriter doesn’t let you specify the encoding directly, so you need a class like this:

public sealed class StringWriterWithEncoding : StringWriter
{
    private readonly Encoding encoding;

    public StringWriterWithEncoding (Encoding encoding)
    {
        this.encoding = encoding;
    }

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

(This question is similar but not quite a duplicate.)

EDIT: To answer the comment: pass the StringWriterWithEncoding to XmlWriter.Create instead of the StringBuilder, then call ToString() on it at the end.

Leave a Comment