XmlSerializer更改编码

MTA*_*MTA 16 .net c# xml

我将此代码用于SerializeXML String:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
    indent = true,
    Encoding = Encoding.UTF8
};

using (var sw = new StringWriter())
{
    using (XmlWriter xmlWriter = XmlWriter.Create(sw, xmlWriterSettings))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(moviesObject.GetType(), new XmlRootAttribute("category"));
        xmlSerializer.Serialize(xmlWriter, moviesObject);
    }
    return sw.ToString();
}
Run Code Online (Sandbox Code Playgroud)

问题是我得到:

<?xml version="1.0" encoding="utf-16"?>
<category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" havemore="no">
  <items>
    <movie>
      <videoid>videoid1</videoid>
      <title>title1</title>
    </movie>
  </items>
</category>
Run Code Online (Sandbox Code Playgroud)

有什么办法可以改变<?xml version="1.0" encoding="utf-16"?> 到 <?xml version="1.0" encoding="utf-8"?>?

pep*_*epo 17

这是一个编码为参数的代码.请阅读注释为什么有一个SuppressMessage进行代码分析.

/// <summary>
/// Serialize an object into an XML string
/// </summary>
/// <typeparam name="T">Type of object to serialize.</typeparam>
/// <param name="obj">Object to serialize.</param>
/// <param name="enc">Encoding of the serialized output.</param>
/// <returns>Serialized (xml) object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal static String SerializeObject<T>(T obj, Encoding enc)
{
    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings()
        {
            // If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose
            // Code analysis does not understand that. That's why there is a suppress message.
            CloseOutput = false, 
            Encoding = enc,
            OmitXmlDeclaration = false,
            Indent = true
        };
        using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
        {
            XmlSerializer s = new XmlSerializer(typeof(T));
            s.Serialize(xw, obj);
        }

        return enc.GetString(ms.ToArray());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您的答案如何解决为“编码”设置“XmlWriterSettings”属性似乎没有传播到最终输出的问题?我已经将 `XmlWriterSettings` 的 `Encoding` 属性设置为 `Encoding.UTF8` 并将这个 `XmlWriterSettings` 传递给 `XmlWriter.Create`,但它仍然序列化为 `utf-16`。OP 也有同样的问题。我在你的代码中看不到任何会改变它的东西。什么是缺失的部分? (2认同)
  • 我在这里找到了答案:http://stackoverflow.com/a/4928759/1195273.我使用`StringBuilder`而不是`MemoryStream`.使用`StringBuilder`会忽略`Encoding`设置.谈论隐藏的复杂性 - sheesh! (2认同)
  • @crush 我很高兴你找到了丢失的部分 :) 并且它对你有用。 (2认同)