欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

XML序列化

程序员文章站 2022-04-15 10:49:21
#region 序列化 /// /// XML序列化 /// /// 序列对象 /// XML文件路径 /// 是否成功 public static bool SerializeToXml(object obj, string filePath) { ... ......
#region  序列化

        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="obj">序列对象</param>
        /// <param name="filepath">xml文件路径</param>
        /// <returns>是否成功</returns>
        public static bool serializetoxml(object obj, string filepath)
        {
            bool result = false;

            filestream fs = null;
            try
            {
                fs = new filestream(filepath, filemode.create, fileaccess.write, fileshare.readwrite);
                xmlserializer serializer = new xmlserializer(obj.gettype());
                serializer.serialize(fs, obj);
                result = true;
            }
            catch (exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.close();
            }
            return result;

        }

        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <param name="type">目标类型(type类型)</param>
        /// <param name="filepath">xml文件路径</param>
        /// <returns>序列对象</returns>
        public static object deserializefromxml(type type, string filepath)
        {
            filestream fs = null;
            try
            {
                fs = new filestream(filepath, filemode.open, fileaccess.read, fileshare.readwrite);
                xmlserializer serializer = new xmlserializer(type);
                return serializer.deserialize(fs);
            }
            catch (exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.close();
            }
        }

        #endregion