XML serialization, encoding XML serialization, encoding xml xml

XML serialization, encoding


If you pass the serializer an XmlWriter, you can control some parameters like encoding, whether to omit the declaration (eg for a fragment), etc.

This is not meant to be a definitive guide, but an alternative so you can see what's going on, and something that isn't just going to console first.

Note also, if you create your XmlWriter with a StringBuilder instead of a MemoryStream, your xml will ignore your Encoding and come out as utf-16 encoded. See the blog post writing xml with utf8 encoding for more information.

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings {     Indent = true,     OmitXmlDeclaration = false,     Encoding = Encoding.UTF8 };using (MemoryStream memoryStream = new MemoryStream() )using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings)){       var x = new System.Xml.Serialization.XmlSerializer(p.GetType());    x.Serialize(xmlWriter, p);    // we just output back to the console for this demo.    memoryStream.Position = 0; // rewind the stream before reading back.    using( StreamReader sr = new StreamReader(memoryStream))    {        Console.WriteLine(sr.ReadToEnd());    } // note memory stream disposed by StreamReaders Dispose()}


1) The GetType() function returns a Type object representing the type of your object, in this case the class clsPerson. You could also use typeof(clsPerson) and get the same result. That line creates an XmlSerializer object for your particular class.

2) If you want to change the encoding, I believe there is an override of the Serialize() function that lets you specify that. See MSDN for details. You may have to create an XmlWriter object to use it though, details for that are also on MSDN:

 XmlWriter writer = XmlWriter.Create(Console.Out, settings);

You can also set the encoding in the XmlWriter, the XmlWriterSettings object has an Encoding property.


I took the solution offered by @robert-paulson here for a similar thing I was trying to do and get the string of an XmlSchema. By default it would return as utf-16. However as mentioned the solution here suffers from a Stream Closed Read error. So I tool the liberty of posting the refactor as an extension method with the tweek mentioned by @Liam to move the using block.

    public static string ToXmlString(this XmlSchema xsd)    {        var xmlWriterSettings = new XmlWriterSettings        {            Indent = true,            OmitXmlDeclaration = false,            Encoding = Encoding.UTF8        };        using (var memoryStream = new MemoryStream())        {            using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))            {                xsd.Write(xmlWriter);            }            memoryStream.Position = 0;             using (var sr = new StreamReader(memoryStream))            {                return sr.ReadToEnd();            }        }    }