3

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.

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'll try again and double check.
I ran the code again after changing the encoding to UTF8 and it still outputs an XML doc with UTF-16 specification. I'll change the code to use the using instead of the close.
Well, I'm an idiot. There were two places (events) where I was doing this and I was changing it in one place and testing it from the other event. It works. Changing the encoding in the XmlWriter to UTF8 works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.