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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With