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

            /// <summary>
            /// 将指定对象序列化为xml并写入指定路径
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="path">文件路径</param>
            /// <param name="obj">需要序列化的对象</param>
            /// <param name="isOmitXmlDeclaration">true:省略XML声明;否则为false.默认false,即编写 XML 声明。</param>
            /// <param name="removeDefaultNamespace">是否移除默认名称空间(如果对象定义时指定了:XmlRoot(Namespace = "http://www.xxx.com/xsd")则需要传false值进来)</param>
            public static void XmlSerialize<T>(string path, T obj, bool isOmitXmlDeclaration = false, bool removeDefaultNamespace = true)
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = isOmitXmlDeclaration;
                settings.Encoding = Encoding.UTF8;
                settings.Indent = true;
                settings.IndentChars = "	";
                settings.NewLineOnAttributes = true;
                settings.NewLineChars = "
    ";
                using (XmlWriter xmlwriter = XmlWriter.Create(path, settings))
                {
                    XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
                    if (removeDefaultNamespace)
                    {
                        xmlns.Add(string.Empty, string.Empty); //在XML序列化时去除默认命名空间xmlns:xsd和xmlns:xsi
                    }
                    XmlSerializer ser = new XmlSerializer(typeof(T));
                    ser.Serialize(xmlwriter, obj, xmlns);
                }
            }
  • 相关阅读:
    C#方法重载 -0024
    C#表达式体方法 (expression-bodied method )
    C# 匿名类型 -0022
    C# 不可变类型 -0021
    C# 属性 -0020
    C# readonly和const -0019
    C# 类的静态成员和实例成员 -0018
    C#中类和结构体的区别 -0017
    C#预处理器指令 -0016
    微信小程序TabBar定义和配置
  • 原文地址:https://www.cnblogs.com/yuwuji/p/5918693.html
Copyright © 2011-2022 走看看