Thursday, January 7, 2010

XmlWriter defaults to UTF-16 encoding


Whatever your case, you might find a need to alter the encoding type when you are using the XmlWriter class to anything other than UTF-16 which is the default in .NET. I like simplicity so a quick string manipulation will suffice .

private static string SerializeIt(object item)
{
try
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
XmlSerializer sr = new XmlSerializer(item.GetType());
if (writer != null) sr.Serialize(writer, item);
}
//change the encoding back to UFT-8
sb.Replace(Encoding.Unicode.WebName, Encoding.UTF8.WebName);
return sb.ToString();
}
catch (Exception ex)
{
//do something.
}
}

No comments: