使用dot.net c#序列化和反序列化XML

时间:2011-02-17 05:22:11

标签: c# serialization xmlreader xmlwriter

在过去的几个小时里,我花了很多时间来阅读以下代码,这些代码似乎已经过时了,或者看起来似乎没什么用。

如果对任何人有任何帮助,那么最终的工作代码。如果可以改进,可以免费评论: - )

public class SerializationHelper<T> {

#region static string SerializeObject( T obj, Encoding encoding )

/// <summary>
///   Serialize an [object] to an Xml String.
/// </summary>
/// <typeparam name="T">Object Type to Serialize</typeparam>
/// <param name="obj">Object Type to Serialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Empty.String if Exception, XML string if successful</returns>
/// <example>
///   // UTF-16 Serialize
///   string xml = SerializationHelper<ObjectType>SerializeObject( [object], new UnicodeEncoding( false, false ) );
/// </example>
/// <example>
///   // UTF-8 Serialize
///   string xml = SerializationHelper<ObjectType>SerializeObject( [object], Encoding.UTF8 );
/// </example> 
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 )

/// <summary>
///   Deserialize an Xml String to an [object]
/// </summary>
/// <typeparam name="T">Object Type to Deserialize</typeparam>
/// <param name="xml">Xml String to Deserialize</param>
/// <param name="encoding">System.Text.Encoding Type</param>
/// <returns>Default if Exception, Deserialize object if successful</returns>
/// <example>
///   // UTF-16 Deserialize
///   [object] = SerializationHelper<ObjectType>DeserializeObject( xml, Encoding.Unicode )
/// </example>
/// <example>
///   // UTF-8 Deserialize
///   [object] = SerializationHelper<ObjectType>DeserializeObject( xml, Encoding.UTF8 )
/// </example> 
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     

}

2 个答案:

答案 0 :(得分:0)

我建议将类型参数T移到封闭类并制作XmlSerializer实例static。泛型类中的静态字段是每个封闭类型,因此SerializationHelper<Apple>SerializationHelper<Orange>将各自具有该字段的单独实例。

此外,我不确定catch { return String.Empty; }是否也是最好的主意 - 掩盖问题以避免崩溃让我感到紧张。

答案 1 :(得分:0)

我认为没有必要使用整个编码部分。您只需使用一种编码进行序列化,然后转换为字节,然后转换回Unicode。这是为什么?但我可能会在这里遗漏一些东西。

另一件让我受伤的是.ToArray()用法。如果你有大量的层次结构和序列化的对象,那么这可能会非常重要。尝试使用StreamReader读取内存流,而无需将其复制到Array中。但这需要一些性能测试来支持我的推理。