1. 程式人生 > >C# XML序列化&反序列化

C# XML序列化&反序列化

類庫 System.Xml.Serialization

序列化

    /// <summary>
    /// 序列化
    /// </summary>
    /// <param name="type">型別</param>
    /// <param name="obj">物件</param>
    /// <returns></returns>
    public static string Serializer<T>(T obj)
    {
        string str = string
.Empty; try { using (MemoryStream ms = new MemoryStream()) { using (XmlTextWriter textWriter = new XmlTextWriter(ms, new UTF8Encoding())) { XmlSerializer xml = new XmlSerializer(typeof(T)); // 去掉結點的 xmlns:xsi="" 屬性
var namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); //序列化物件 xml.Serialize(textWriter, obj, namespaces); str = Encoding.UTF8.GetString(ms.GetBuffer()).Trim(); }
} return str; } catch (Exception ex) { return str; } }

反序列化

	/// <summary>
    /// 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="xmlString"></param>
    /// <returns></returns>
    public static T Deserialize<T>(string xmlString)
    {
        try
        {
            using (StringReader st = new StringReader(xmlString))
            {
                var xmlSer = new XmlSerializer(typeof(T));
                return (T)xmlSer.Deserialize(st);
            }
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }