[C#]XML序列化成物件與反序列化

  • 4347
  • 0
  • C#
  • 2016-12-30

XML序列化成物件與反序列化

寫了個泛型筆記一下

功能說明:

  • Serialize 可將object轉成XML字串
  • Deserialize 可將XML字串轉成指定object
/// <summary>
/// XML序列化物件
/// </summary>
public class XmlObjectSerializer
{
    /// <summary>
    /// 將物件序列化成XML格式字串
    /// </summary>
    /// <typeparam name="T">物件型別</typeparam>
    /// <param name="obj">物件</param>
    /// <returns>XML格式字串</returns>
    public string Serialize<T>(T obj) where T : class
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        var stringWriter = new StringWriter();
        using (var writer = XmlWriter.Create(stringWriter))
        {
            serializer.Serialize(writer, obj);
            return stringWriter.ToString();
        }
    }

    /// <summary>
    /// 將XML格式字串反序列化成物件
    /// </summary>
    /// <typeparam name="T">物件型別</typeparam>
    /// <param name="xmlString">XML格式字串</param>
    /// <returns>反序列化後的物件</returns>
    public T Deserialize<T>(string xmlString) where T : class
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(T));
        using (TextReader reader = new StringReader(xmlString))
        {
            object deserializationObj = deserializer.Deserialize(reader);
            return deserializationObj as T;
        };
    }
}

 

參考:

http://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part

 

 

一天一分享,身體好健康。

該追究的不是過去的原因,而是現在的目的。