且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以utf-8而不是utf-16返回xml

更新时间:2023-11-24 21:05:52

响应的编码

我对框架的这一部分不太熟悉.但是根据MSDN,您可以设置:

httpContextBase.Response.ContentEncoding = Encoding.UTF8;

XmlSerializer看到的

编码

再次阅读您的问题后,我发现这是困难的部分.问题在于使用StringWriter.因为.NET字符串始终存储为UTF-16(需要引用,请^^),因此StringWriter将此作为其编码返回.因此,XmlSerializer将XML声明写为

Encoding as seen by the XmlSerializer

After reading your question again I see that this is the tough part. The problem lies within the use of the StringWriter. Because .NET Strings are always stored as UTF-16 (citation needed ^^) the StringWriter returns this as its encoding. Thus the XmlSerializer writes the XML-Declaration as

<?xml version="1.0" encoding="utf-16"?>

要解决此问题,您可以像这样写入MemoryStream:

To work around that you can write into an MemoryStream like this:

using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
    XmlSerializer xml = new XmlSerializer(typeof(T));
    xml.Serialize(writer, Data);

    // I am not 100% sure if this can be optimized
    httpContextBase.Response.BinaryWrite(stream.ToArray());
}

其他方法

另一种我刚刚注意到由jtm001链接的这样的答案.浓缩的解决方案是为XmlSerializer提供一个自定义的XmlWriter,该XmlWriter被配置为使用UTF8作为编码.

Another edit: I just noticed this SO answer linked by jtm001. Condensed the solution there is to provide the XmlSerializer with a custom XmlWriter that is configured to use UTF8 as encoding.

Athari 建议StringWriter派生,并将其广告编码为UTF8.

Athari proposes to derive from the StringWriter and advertise the encoding as UTF8.

据我了解,这两种解决方案也都应该起作用.我认为这里的要点是您将需要一种样板代码或另一种样板代码.

To my understanding both solutions should work as well. I think the take-away here is that you will need one kind of boilerplate code or another...