首页 > Windows开发 > 详细

c# 序列化对象为xml 方法

时间:2018-05-04 19:22:13      阅读:170      评论:0      收藏:0      [点我收藏+]

 

        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();
        }

 

c# 序列化对象为xml 方法

原文:https://www.cnblogs.com/axel10/p/8992161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!