.net本身是utf16编码格式,需要应用utf8编码格式或者其他编码格式的简单实现。
public sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding() : this(Encoding.UTF8) { }
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}
/// <summary>
/// Serialize class instance to XML string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="namespaces"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string SerializeEncoding<T>(T instance, XmlSerializerNamespaces namespaces, Encoding encoding = null)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
if (encoding == null)
encoding = Encoding.UTF8;
using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(encoding))
{
xmlSerializer.Serialize(stringWriter, instance, namespaces);
return stringWriter.ToString();
}
}