您的足迹:首页 > .NET >xml序列化和反序列化代码

xml序列化和反序列化代码

xml序列化和反序列化代码

    public class XmlUtil
    {
        #region 反序列化 

        /// <summary> 
        /// 反序列化 
        /// </summary> 
        /// <param name="type">类型</param> 
        /// <param name="xml">XML字符串</param> 
        /// <returns></returns> 
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);

                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {
                return null;

            }
        }
        #endregion

        #region 序列化 

        /// <summary> 
        /// 序列化 
        /// </summary> 
        /// <param name="type">类型</param> 
        /// <param name="obj">对象</param> 
        /// <returns></returns> 
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象 
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }

            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();
            
            return str;
        }
        #endregion
    }

本博客所有文章如无特别注明均为原创。作者:cc复制或转载请以超链接形式注明转自 .NET程序员之路
原文地址《xml序列化和反序列化代码

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)