实体类序列化和反序列化

            昨日在工作时,遇到一需求,需要把实体类的实例以XML格式存入SQL SERVER的XML类型的字段中。直接上代码。

说明: Serialize方法把实体实例序列化成xml格式的字符串返回。最后 “returnStr.Substring(38,returnStr.Length-38);” 是为了解决在存入数据库时报的错误,因为序列化出来后,是包含<?xml version="1.0" encoding="utf-8"?>信息头的,在保存进入数据库时会报“XML 分析: 行 1,字符 38,无法切换编码”的错误,因此需要去掉。从数据库取出来,反序列化没有该信息头是不会报错的。

 

private static Dictionary<int, XmlSerializer> serializer_dict = new Dictionary<int, XmlSerializer>();

        public static XmlSerializer GetSerializer(Type t)
        {
            int type_hash = t.GetHashCode();
            if (!serializer_dict.ContainsKey(type_hash))
                serializer_dict.Add(type_hash, new XmlSerializer(t));
            return serializer_dict[type_hash];
        }

        /// <summary>
        /// 实?体?序?列?化?成?XML源?文?件?
        /// </summary>
        /// <param name="obj">对?象?</param>
        /// <returns>xml源?文?件?字?符?串?</returns>
        public static string Serialize(object obj)
        {
            string returnStr = "";
            XmlSerializer serializer = GetSerializer(obj.GetType());
            MemoryStream ms = new MemoryStream();
            XmlTextWriter xtw = null;
            StreamReader sr = null;
            try
            {
                xtw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
                xtw.Formatting = System.Xml.Formatting.Indented;
                serializer.Serialize(xtw, obj);
                ms.Seek(0, SeekOrigin.Begin);
                sr = new StreamReader(ms);
                returnStr = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
                if (sr != null)
                    sr.Close();
                ms.Close();
            }
            return returnStr.Substring(38,returnStr.Length-38);
        }

        /// <summary>
        /// XML源?文?件?反?序?列?化?成?实?体?
        /// </summary>
        /// <param name="type">实?体?类?型?</param>
        /// <param name="s">XML源?文?件?</param>
        /// <returns></returns>
        public static object DeSerialize(Type type, string s)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
            try
            {
                XmlSerializer serializer = GetSerializer(type);
                return serializer.Deserialize(new MemoryStream(b));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
posted @ 2011-08-10 14:18  糊涂而已  阅读(2332)  评论(0编辑  收藏  举报