你的位置:首页 > ASP.net教程

[ASP.net教程]XML序列化与反序列化


    利用泛型实现

    1、序列化

    /// <summary>    /// 将一个对象序列化为string    /// </summary>    /// <typeparam name="T">对象类型</typeparam>    /// <param name="o">待序列化的对象</param>    /// <returns>序列化后的字符串</returns>    public static string To(T o)    {      = new typeof(T));      = new = string.Empty;      using (StringWriter sw = new StringWriter())      {        xs.Serialize(sw, o, = sw.ToString();      }      return result;    }

    2、反序列化

    /// <summary>    /// 将string反序列化为一个对象    /// </summary>    /// <typeparam name="T">对象类型</typeparam>    /// <param name="    /// <returns>反序列化后的对象</returns>    public static T From(string = default(T);      if (string.IsNullOrWhiteSpace(return result;      }      = new typeof(T));      using (StringReader sr = new StringReader(= xs.Deserialize(sr) as T;      }      return result;    }