C# xml序列化实现及遇到的坑

  ///

  /// 对象转化为xml字符串

  ///

  ///

  /// 是否需要xml声明头,默认不需要

  /// 是否需要格式化xml,默认不需要

  ///

  public static string ObjectToXmlString(object obj, bool isNeedHeader = false, bool isFormat = false)

  {

  try

  {

  XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());

  XmlWriterSettings settings = new XmlWriterSettings();

  settings.Encoding = new UTF8Encoding(false);//utf-8不带BOM //Encoding.UTF8;//utf-8带BOM

  if (isFormat)

  {

  settings.Indent = true;

  settings.IndentChars = " ";

  settings.NewLineChars = "

  ";

  }

  if (!isNeedHeader)

  {

  settings.OmitXmlDeclaration = true; // 不生成声明头

  }

  using (var memoryStream = new MemoryStream())

  using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, settings))

  {

  // 强制指定命名空间,覆盖默认的命名空间

  XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();

  namespaces.Add(string.Empty, string.Empty);

  xmlSerializer.Serialize(xmlWriter, obj, namespaces);

  var xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());

  return xmlString;

  };

  }

  catch

  {

  return string.Empty;

  }

  }