XmlSerializer更改编码

我正在使用此代码将XML Serialize String

 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { indent = true, Encoding = Encoding.UTF8 }; using (var sw = new StringWriter()) { using (XmlWriter xmlWriter = XmlWriter.Create(sw, xmlWriterSettings)) { XmlSerializer xmlSerializer = new XmlSerializer(moviesObject.GetType(), new XmlRootAttribute("category")); xmlSerializer.Serialize(xmlWriter, moviesObject); } return sw.ToString(); } 

问题是,我得到:

     videoid1 title1    

有什么方法可以将更改为

这是一个编码为参数的代码。 请阅读注释为什么有一个SuppressMessage进行代码分析。

 ///  /// Serialize an object into an XML string ///  /// Type of object to serialize. /// Object to serialize. /// Encoding of the serialized output. /// Serialized (xml) object. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] internal static String SerializeObject(T obj, Encoding enc) { using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { // If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose // Code analysis does not understand that. That's why there is a suppress message. CloseOutput = false, Encoding = enc, OmitXmlDeclaration = false, Indent = true }; using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, xmlWriterSettings)) { XmlSerializer s = new XmlSerializer(typeof(T)); s.Serialize(xw, obj); } return enc.GetString(ms.ToArray()); } } 

试试这个

 public static void SerializeXMLData(string pth, object xmlobj) { XmlSerializer serializer = new XmlSerializer(xmlobj.GetType()); using (XmlTextWriter tw = new XmlTextWriter(pth, Encoding.UTF8)) { tw.Formatting = Formatting.Indented; serializer.Serialize(tw, xmlobj); } } 

解决方案很简单:
使用派生自StringWriter的StringWriter类,并在构造函数中设置编码,并覆盖基类的Encoding属性:

 public sealed class StringWriterWithEncoding : System.IO.StringWriter { private readonly System.Text.Encoding encoding; public StringWriterWithEncoding(System.Text.StringBuilder sb) : base(sb) { this.encoding = System.Text.Encoding.Unicode; } public StringWriterWithEncoding(System.Text.Encoding encoding) { this.encoding = encoding; } public StringWriterWithEncoding(System.Text.StringBuilder sb, System.Text.Encoding encoding) : base(sb) { this.encoding = encoding; } public override System.Text.Encoding Encoding { get { return encoding; } } } 

然后只需将StringWriterWithEnccoding的实例传递给您的方法:

 public static string SerializeToXml(T ThisTypeInstance) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); string strReturnValue = null; //SerializeToXml(ThisTypeInstance, new System.IO.StringWriter(sb)); SerializeToXml(ThisTypeInstance, new StringWriterWithEncoding(sb, System.Text.Encoding.UTF8)); strReturnValue = sb.ToString(); sb = null; return strReturnValue; } // End Function SerializeToXml