• 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();
            }
  • 相关阅读:
    从书上学的东西(顺带总结一发)
    网上讲的好的知识点汇总
    土地征用题解(兼斜率优化详解)
    Blocks题解(区间dp)
    高精度模板汇总
    动态规划总结
    异或序列(题解)(莫队)
    小Z的袜子(题解)(莫队)
    小B的询问(题解)(莫队)
    凸包模板——Graham扫描法
  • 原文地址:https://www.cnblogs.com/axel10/p/8992161.html
Copyright © 2020-2023  润新知