C# – How to Specify XML Encoding when Serializing an Object in C#

cencodingutf-8xml

I am serializing a C# object into an XML document and sending the XML document to a third party vendor. The vendor is telling me that the encoding specification in the document is UTF-16, but the XML document contains UTF-8 content and they can't use it. Here is the code I am using to create the XML file, which runs without error and creates an XML document.

// Instantiate xmlSerializer with my object type.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));

// Instantiate a new stream and pass file location and mode.
Stream stream = new FileStream(@"C:\doc.xml", FileMode.Create);

// Instantiate xmlWriter and pass stream and encoding.
XmlWriter xmlWriter = new XmlTextWriter(stream, Encoding.Unicode);

// Call serialize method and pass xmlWriter and my object.
xmlSerializer.Serialize(xmlWriter, myObject);

// Close writer and stream.
xmlWriter.Close();
stream.Close();

When I run this, the XML Doc shows this on the first line:

<?xml version="1.0" encoding="UTF-16"?>

I've tried changing the Encoding from Encoding.Unicode to Encoding.UTF8 in the XmlTextWriter, but that doesn't change the first line of the XML Doc and it still shows UTF-16.

I also tried using the Serialize method signature that takes 4 parameters (writer, object, namespaces, encoding) and specified UTF8 as the encoding and that didn't change the XML Doc specification either.

I believe all I need to do is change the encoding that shows in the XML Doc to UTF-8 and the third party vendor will be happy. I can't figure out what I am doing wrong.

Best Answer

If I change from Encoding.Unicode to Encoding.UTF8, the file is generated properly. Perhaps you're looking at an old version of your file?

In an unrelated bit, you should use using for deterministic disposal of objects which implement IDisposable:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));

using (Stream stream = new FileStream(@".\doc.xml", FileMode.Create))
using (XmlWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8))
{
    xmlSerializer.Serialize(xmlWriter, myObject);
}