原创  C# XML和Object相互转化

分类: 2015-01-27T23:03:54    265人阅读   
 /// <summary>
    ///     序列化工具
    /// </summary>
    public static class SerializeUtls
    {
        /// <summary>
        /// 把对象列化成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {

            DataContractSerializer dcs = new DataContractSerializer(t.GetType());
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(sb))
            {
                dcs.WriteObject(writer, t);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="s">对象序列化后的Xml字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string s)
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(T));

            TextReader tr = new StringReader(s);
            using (XmlReader reader = XmlReader.Create(tr))
            {
                var obj = dcs.ReadObject(reader);

                return (T)obj;
            }
        }
分享到: