zoukankan      html  css  js  c++  java
  • c# 序列化对象为xml 方法

            public static string XmlUtils(object obj, bool omitXmlDeclaration = true, bool indent = false,
                bool useNameSpace = false)
            {
                var sb = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings()
                {
                    OmitXmlDeclaration = omitXmlDeclaration, //是否省略xml声明
                    ConformanceLevel = ConformanceLevel.Auto,
                    Indent = indent //生成的xml是否缩进
                }))
                {
                    if (useNameSpace)
                    {
                        var xs = new XmlSerializer(obj.GetType());
                        xs.Serialize(xw, obj);
                    }
                    else
                    {
                        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                        namespaces.Add(string.Empty, string.Empty); //去除xml命名空间
    
                        var xs = new XmlSerializer(obj.GetType());
                        xs.Serialize(xw, obj, namespaces);
                    }
                }
    
                //...:nil="true"表示该值为空
                return sb.ToString();
            }

     也可以做成扩展方法

            public static string XmlUtils(this T obj, bool omitXmlDeclaration = true, bool indent = false,
                bool useNameSpace = false)
            {
                var sb = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings()
                {
                    OmitXmlDeclaration = omitXmlDeclaration, //是否省略xml声明
                    ConformanceLevel = ConformanceLevel.Auto,
                    Indent = indent //生成的xml是否缩进
                }))
                {
                    if (useNameSpace)
                    {
                        var xs = new XmlSerializer(obj.GetType());
                        xs.Serialize(xw, obj);
                    }
                    else
                    {
                        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                        namespaces.Add(string.Empty, string.Empty); //去除xml命名空间
    
                        var xs = new XmlSerializer(obj.GetType());
                        xs.Serialize(xw, obj, namespaces);
                    }
                }
    
                //...:nil="true"表示该值为空
                return sb.ToString();
            }
  • 相关阅读:
    学习过程之python跳一跳
    OSError: [WinError -2147221003] 找不到应用程序: 'QR.png' 的解决方法
    易知大学 任务25 第一次爬虫与测试
    linux常用命令
    健身日志
    JavaScript JSON
    常用注解 开发SpringBoot项目
    网络基础
    jQuery MINI UI 学习之分页查询
    Springboot集成ActivitiModel提示输入密码
  • 原文地址:https://www.cnblogs.com/axel10/p/8992161.html
Copyright © 2011-2022 走看看