7

I use a TextWriter to serialize, because it's easy to switch between string serialization and file serialization:

Serialize to string;

TextWriter stringWriter = new StringWriter();
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

Serialize to file;

TextWriter fileWriter = new StreamWriter(targetXMLFileName, true, Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(fileWriter , objetToSerialize)
fileWriter.Close();

My problem is that when serializing to string, it creates a UTF-16 ("?xml version="1.0" encoding="utf-16"?"), and TestWriter encoding property is ReadOnly

I have tried:

var memoryStream = new MemoryStream();
TextWriter stringWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

But it doesn't work. Instead of an XML Document it produces this string: "System.IO.StreamWriter" O_o

How can I initialize the TextWriter to UTF-8 Encoding

Kaikus
  • 1,001
  • 4
  • 14
  • 26
  • My answer to a similar question: http://stackoverflow.com/a/24075012 – Sami Kuhmonen Jan 28 '16 at 20:33
  • 1
    You can use `Utf8StringWriter` from http://stackoverflow.com/questions/3862063/serializing-an-object-as-utf-8-xml-in-net/3862106#3862106 – dbc Jan 28 '16 at 22:05
  • Possible duplicate: [Serializing an object as UTF-8 XML in .NET](http://stackoverflow.com/questions/3862063/serializing-an-object-as-utf-8-xml-in-net) – dbc Jan 28 '16 at 22:45

1 Answers1

9

Instead of stringWriter.ToString, use

string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
return xml;

That will convert the memory stream you wrote to, to a printable XML with utf-8 in the header.

EventHorizon
  • 2,916
  • 22
  • 30