While trying to answer another question, I was serializing a C# object to an XML string. It was surprisingly hard; this was the shortest code snippet I could come up with:<
Simply if you want to use UTF8 encoding then do it like this
public class StringWriterUtf8 : System.IO.StringWriter
{
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
and then use StringWriterUtf8 insread of StringWriter like this
using (StringWriterUtf8 textWriter = new StringWriterUtf8())
{
serializer.Serialize(textWriter, tr, ns);
xmlText = textWriter.ToString();
}