C#XmlSerializer强制编码类型为ISO-8859-1

时间:2014-11-14 16:05:27

标签: c# encoding xml-serialization

我在序列化对象时尝试将编码类型设置为ISO-8859-1。代码运行时不会抛出任何异常,但返回的编码类型始终设置为“UTF-16”。我搜索了很多例子,有100个样本,但我根本无法强制所需的编码类型。

我的问题是如何强制它将编码设置为ISO-8859-1?

提前致谢。

代码是:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = false,
    Encoding = Encoding.GetEncoding("ISO-8859-1")
};

using (var stringWriter = new StringWriter())
{
    using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
    {
        serializer.Serialize(xmlWriter, obj, ns);
    }

    return stringWriter.ToString();
}

1 个答案:

答案 0 :(得分:11)

当您将XML写入TextWriter(例如StringWriterStreamWriter)时,它始终使用TextWriter指定的编码,并忽略XmlWriterSettings中指定的编码{1}}。对于StringWriter,编码始终是UTF-16,因为这是.NET字符串在内存中使用的编码。

解决方法是写入MemoryStream并从那里读取字符串:

var encoding = Encoding.GetEncoding("ISO-8859-1");
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = false,
    Encoding = encoding
};

using (var stream = new MemoryStream())
{
    using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
    {
        serializer.Serialize(xmlWriter, obj, ns);
    }
    return encoding.GetString(stream.ToArray());
}

请注意,如果您在字符串中包含XML,则在将其写入文件时,您需要确保使用相同的编码进行编写。