Force XDocument to write to String with UTF-8 encoding

Try this:

using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml",
                                       LoadOptions.PreserveWhitespace);
        doc.Declaration = new XDeclaration("1.0", "utf-8", null);
        StringWriter writer = new Utf8StringWriter();
        doc.Save(writer, SaveOptions.None);
        Console.WriteLine(writer);
    }

    private class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }
}

Of course, you haven’t shown us how you’re building the document, which makes it hard to test… I’ve just tried with a hand-constructed XDocument and that contains the relevant whitespace too.

Leave a Comment