【发布时间】:2012-10-27 20:55:26
【问题描述】:
我有一个非常适用于 ASCII 的 XML 序列化程序,但是当遇到非 ASCII 字符时,它们会被替换为问号“?”。我相信我已经为 UTF8 正确配置了它,但我不确定它为什么这样做。
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
settings.NewLineChars = "\n";
settings.NewLineHandling = NewLineHandling.None;
settings.NewLineOnAttributes = false;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
{
xmls.Serialize(writer, obj, ns);
}
string xml = Encoding.UTF8.GetString(ms.ToArray());
// remove the BOM character at the beginning which screws up decoding
if (xml.Length > 0 && xml[0] != '<')
{
xml = xml.Substring(1, xml.Length - 1);
}
return xml;
}
【问题讨论】:
-
您确定这些字符实际上是问号,并且您使用的文本编辑器根本不知道如何表示非 ASCII 字符(因此显示一个问号)?
-
@haxor 我刚刚用“Jalapeño”测试了上述内容 - 工作正常;不过,您的 BOM 删除有点狡猾
-
顺便说一句,
XmlTextWriter.Create实际上是XmlWriter.Create -
请展示一个具体示例(即可运行)来演示您所看到的问题,即使用示例 DTO 类和示例非 ASCII 字符串。我无法重现该问题。
-
k;不过,我确实建议您调整摆脱 BOM 的方式
标签: c# xml xmlserializer