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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
  • 2021-12-10
  • 2021-10-29
  • 2021-06-09
  • 2021-10-12
  • 2021-09-12
猜你喜欢
  • 2022-01-27
  • 2022-02-06
  • 2021-12-18
  • 2021-06-26
  • 2022-12-23
  • 2021-10-09
  • 2022-12-23
相关资源
相似解决方案