Force XDocument to write to String with UTF-8 encoding Force XDocument to write to String with UTF-8 encoding xml xml

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.


Try XmlWriterSettings:

XmlWriterSettings xws = new XmlWriterSettings();xws.OmitXmlDeclaration = false;xws.Indent = true;

And pass it on like

using (XmlWriter xw = XmlWriter.Create(sb, xws))


See also https://stackoverflow.com/a/3288376/1430535

return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();