C# XML序列化与反序列化实现.util

XML序列化与反序列化实现

序列化与反序列化

XML序列化

代码如下

		/// <summary>
        /// 实体对象序列化成xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            return Serialize<T>(obj, Encoding.UTF8);
        }

        /// <summary>
        /// 实体对象序列化成xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj, Encoding encoding)
        {
            try
            {
                if (obj == null)
                    throw new ArgumentNullException("obj");

                var ser = new XmlSerializer(obj.GetType());
                using (var ms = new MemoryStream())
                {
                    using (var writer = new XmlTextWriter(ms, encoding))
                    {
                        writer.Formatting = Formatting.Indented;
                        ser.Serialize(writer, obj);
                    }
                    var xml = encoding.GetString(ms.ToArray());
                    /*
                     *  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"中xsi的意思是 :
                        本xml文件中要用到某些来自xsi代表的“http://www.w3.org/2001/XMLSchema-instance”这个命名空间的元素 
                        比如用来引入无命名空间schema文件的noNamespaceSchemaLocation="XXX";
                        以及引入自带命名空间的schema文件的schemaLocation="XXX"这些元素。
                        这些元素是包含在xsi命名空间中的,所有的xml文件只要引用这些元素 就要引入xsi这个命名空间。  
                        xsi这三个字母不是硬性规定,只是大家都这么用,方便阅读而已
                        可以选择删掉也也可以选择保留
                     */
                    //xml = xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
                    //xml = xml.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
                    return xml;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

XML反序列化

支持xml文本,文件流按不同编码方式转为对象
代码如下

		/// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string xml) where T : new()
        {
            return DeSerialize<T>(xml, Encoding.UTF8);
        }
        /// <summary>
        /// 反序列化xml字符为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string xml, Encoding encoding) where T : new()
        {
            try
            {
                var mySerializer = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream(encoding.GetBytes(xml)))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        return (T)mySerializer.Deserialize(sr);
                    }
                }
            }
            catch (Exception)
            {
                return default;
            }

        }

        public static object Deserialize<T>(Stream stream)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));

            return xs.Deserialize(stream);
        }

XML文件保存与读取

文件保存为name.xml

        public static bool SaveXmlFile(object obj, string path)
        {
            try
            {
                string xml = Serialize(obj);
                using (StreamWriter writer = File.CreateText(path))
                {
                    writer.Write(xml);  //写入文件中
                    writer.Flush();
                    writer.Close();
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return true;
        }

读取.xml文件

支持将读取的.xml文件返回xmlString,object对象类型

		public static string LoadXmlFile(string path)
        {
            return LoadXmlFile(path, Encoding.UTF8);
        }
        public static string LoadXmlFile(string path, Encoding encoding)
        {
            StringBuilder xml = new StringBuilder();
            using (StreamReader reader = new StreamReader(path))
            {
                while (reader.EndOfStream != true)
                {
                    xml.Append(reader.ReadLine());
                }
            }

            return xml.ToString();
        }
        public static T LoadXmlFile<T>(string path) where T : new()
        {
            return LoadXmlFile<T>(path, Encoding.UTF8);
        }
        public static T LoadXmlFile<T>(string path, Encoding encoding) where T : new()
        {
            string xml = LoadXmlFile(path, encoding);
            return DeSerialize<T>(xml, encoding);
        }

参考文献

[1] C#读取XML文件,反序列化为指定对象_生面别开-CSDN博客
[2] c# where(泛型类型约束) - 墨竹daisy - 博客园

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值