zoukankan      html  css  js  c++  java
  • XML序列化与反序列化

    C#对于XML的序列化与反序列化提供了很好的支持,我们只需要引用System.Xml的命名空间即可,无需使用第三方库,下面简单实现了一个XML的序列化与反序列化的帮助类。

    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace XmlHelper
    {
        public static class XmlSerializeHelper
        {
            /// <summary>
            /// XML序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string XmlSerializer<T>(T obj)
            {          
                var settings = new XmlWriterSettings
                {
                    Encoding = new UTF8Encoding(false),
                    Indent = true
                };
    
                using (var ms = new MemoryStream())
                {                           
                    using (var xw = XmlWriter.Create(ms, settings))
                    {
                        var ns = new XmlSerializerNamespaces();
                        ns.Add("", "");
                        var serializer = new XmlSerializer(obj.GetType());
                        serializer.Serialize(xw, obj, ns);
                        return Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
    
            /// <summary>
            /// XML反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="XmlString"></param>
            /// <returns></returns>
            public static T XmlDeserialize<T>(this string XmlString)
            {
                if (string.IsNullOrEmpty(XmlString))
                    throw new ArgumentNullException("s");         
    
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(XmlString)))
                {
                    using (var xr = XmlReader.Create(ms))
                    {
                        var xmlSerializer = new XmlSerializer(typeof(T));
                        return (T)xmlSerializer.Deserialize(xr);
                    }
                }
            }
    
        }
    }
  • 相关阅读:
    C#异步编程:多线程基础Thread类
    WPF:TextBox控件禁用中文输入
    C#:泛型的协变和逆变
    C#:泛型接口
    C#:泛型委托
    C#:泛型类
    Jetbrains Rider:缺少.NET Framework 4.5.2
    C#:泛型方法
    C#:泛型
    C#:接口
  • 原文地址:https://www.cnblogs.com/sunwenqi/p/11044009.html
Copyright © 2011-2022 走看看