c# - XmlSerializer 改变编码

标签 c# .net xml

我正在使用此代码来 Serialize XML 到 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();
}

问题是我得到:

<?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>

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

最佳答案

这是一个以编码为参数的代码。代码分析为什么有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());
    }
}

关于c# - XmlSerializer 改变编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22453036/

相关文章:

c# - RazorEngine 变量解析问题

c# - 序列化和版本控制

xml - 如何在 Progress 4GL 中发送 SOAP header

java - 以 XML 格式导出 SQLite 表

c# - mscorlib.dll : Access to the path . 中发生类型为 'System.UnauthorizedAccessException' 的未处理异常。被拒绝

c# - 如何使用实现类类型的参数创建抽象方法

c# - 在 .NET 中使用 ConfigureAwait

c# - 在 Windows Phone 上检测流或字节数组编码

c# - 在 aspx 页面之间传递 C# 对象

c# - 用十进制表示法替换所有十六进制数