zoukankan      html  css  js  c++  java
  • C#.net XML的序列化与反序列化

            /// <summary>
            /// 将一个对象序列化为XML字符串
            /// </summary>
            /// <param name="o">要序列化的对象</param>
            /// <param name="encoding">编码方式</param>
            /// <returns>序列化产生的XML字符串</returns>
            public static string SerializeObject(object o, Encoding encoding)
            {
                if (o == null)
                {
                    throw new ArgumentNullException("o");
                }
                if (encoding == null)
                {
                    throw new ArgumentNullException("encoding");
                }
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlSerializer serializer = new XmlSerializer(o.GetType());
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    settings.NewLineChars = "
    ";
                    settings.Encoding = encoding;
                    settings.IndentChars = "    ";
                    using (XmlWriter writer = XmlWriter.Create(stream, settings))
                    {
                        serializer.Serialize(writer, o);
                        writer.Close();
                    }
                    stream.Position = 0;
                    using (StreamReader reader = new StreamReader(stream, encoding))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
    
            /// <summary>
            /// 从XML字符串中反序列化对象
            /// </summary>
            /// <typeparam name="T">结果对象类型</typeparam>
            /// <param name="xmlString">包含对象的XML字符串</param>
            /// <param name="encoding">编码方式</param>
            /// <returns>反序列化得到的对象</returns>
            public static T DeserializeObject<T>(string xmlString, Encoding encoding)
            {
                if (string.IsNullOrEmpty(xmlString))
                {
                    throw new ArgumentNullException("s");
                }
                if (encoding == null)
                {
                    throw new ArgumentNullException("encoding");
                }
    
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(encoding.GetBytes(xmlString)))
                {
                    using (StreamReader sr = new StreamReader(ms, encoding))
                    {
                        return (T)serializer.Deserialize(sr);
                    }
                }
            }
  • 相关阅读:
    Vue的条件渲染详解
    Vue的style绑定
    Vue的class绑定总结
    v-model详解
    MUI手势锁
    mysql主从搭建
    处理绿盟科技安全评估的系统漏洞
    微信小程序发送ajax
    微信小程序上拉下拉刷新
    微信小程序覆盖自定义组件样式
  • 原文地址:https://www.cnblogs.com/godbell/p/7190618.html
Copyright © 2011-2022 走看看