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 = Encoding.UTF8;
        if (isFormat)
        {
            settings.Indent = true;
            settings.IndentChars = "    ";
            settings.NewLineChars = "\r\n";
        }
        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;
    }
}

但是发现请求头前面有东西,因为他和普通输入的尖括号不一样,下面的两句代码看着是一样的但是具体运行起来就不一样了

var a1= Encoding.UTF8.GetBytes("<");
var a2 = Encoding.UTF8.GetBytes("<");

在这里插入图片描述
通过转化为byte查看,他俩字节长度都不一样
C# xml序列化以及遇到的坑_第1张图片
第二个比第一个多了三个特殊的字符,经过了解,239 187 191是utf-8 bom的前缀,所以xml序列化之后是utf-8 bom格式的,现在需要不是bom格式的,经过百度学习,发现new UTF8Encoding(false);这样的utf-8生成的字符串就不是带BOM得了,所以修改代码如下

/// 
/// 对象转化为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 = "\r\n";
        }
        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;
    }
}

你可能感兴趣的:(dotnet,c#,xml,java)