使用dot.net c#序列化和反序列化XML
我花了几个小时的时间来阅读以下代码,看了很多似乎过时或看起来似乎没有工作的代码。
如果它对任何人的任何帮助是最终的工作代码。 如果可以改进,可以免费评论:-)
public class SerializationHelper { #region static string SerializeObject( T obj, Encoding encoding ) /// /// Serialize an [object] to an Xml String. /// /// Object Type to Serialize /// Object Type to Serialize /// System.Text.Encoding Type /// Empty.String if Exception, XML string if successful /// /// // UTF-16 Serialize /// string xml = SerializationHelperSerializeObject( [object], new UnicodeEncoding( false, false ) ); /// /// /// // UTF-8 Serialize /// string xml = SerializationHelperSerializeObject( [object], Encoding.UTF8 ); /// public static string SerializeObject( T obj, Encoding encoding ) { if ( obj == null ) { return string.Empty; } try { XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) ); using ( MemoryStream memoryStream = new MemoryStream() ) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() { Encoding = encoding }; using ( XmlWriter writer = XmlWriter.Create( memoryStream, xmlWriterSettings ) ) { xmlSerializer.Serialize( writer, obj ); } return encoding.GetString( memoryStream.ToArray() ); } } catch { return string.Empty; } } #endregion #region static T DeserializeObject( string xml, Encoding encoding ) /// /// Deserialize an Xml String to an [object] /// /// Object Type to Deserialize /// Xml String to Deserialize /// System.Text.Encoding Type /// Default if Exception, Deserialize object if successful /// /// // UTF-16 Deserialize /// [object] = SerializationHelperDeserializeObject( xml, Encoding.Unicode ) /// /// /// // UTF-8 Deserialize /// [object] = SerializationHelperDeserializeObject( xml, Encoding.UTF8 ) /// public static T DeserializeObject( string xml, Encoding encoding ) { if ( string.IsNullOrEmpty( xml ) ) { return default( T ); } try { XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) ); using ( MemoryStream memoryStream = new MemoryStream( encoding.GetBytes( xml ) ) ) { // No settings need modifying here XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); using ( XmlReader xmlReader = XmlReader.Create( memoryStream, xmlReaderSettings ) ) { return (T)xmlSerializer.Deserialize( xmlReader ); } } } catch { return default( T ); } } #endregion }
我建议将类型参数T
移动到封闭类并使XmlSerializer
实例static
。 generics类中的静态字段是每个闭合类型,因此SerializationHelper
和SerializationHelper
将各自具有该字段的单独实例。
另外,我不确定catch { return String.Empty; }
也是最好的主意 – 掩盖问题以避免崩溃让我感到紧张。
我认为没有必要使用整个编码部分。 您只需使用一种编码进行序列化,然后转换为字节,然后转换回Unicode。 这是为什么? 但我可能会在这里遗漏一些东西。
打击我的另一件事是.ToArray()用法。 如果你有很大的层次结构和序列化的对象,这可能会非常重要。 尝试使用StreamReader读取内存流,而无需将其复制到Array中。 但这需要一些性能测试来支持我的推理。