XML Serializer [英] XML Serializer
问题描述
如何使用xml编码utf-16和BOM将xml类对象序列化为字符串?我使用xmlserializer.Serialize(字符串,对象),但它没有BOM?
没有BOM,其他需要将字符串解析为xml的应用程序无法知道wat编码和字符串是否在endian中?
谢谢
你好,
试试这样的事:
< pre lang ="xc#"> using(Stream s = new MemoryStream())
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Encoding = Encoding.Unicode;
using(XmlWriter w = XmlWriter.Create(s,ws))
{
xmlserializer.Serialize(w,myobject);
}
}
请注意,您必须在Stream上使用XmlWriter。在StringBuilder或TextWriter上使用它不会产生BOM,因为这些类使用UTF-16作为默认值,并且BOM无法在其中表示。当通过Stream创建时,作者将自动生成BOM。
谢谢,
Hi,
How to serialize a xml class object to string with xml encoding utf-16 and with BOM? I am using xmlserializer.Serialize(string, object) but it does not have the BOM?
Without the BOM, other application which need to parse the string to xml can't know wat encoding and endian the string is in?
Thanks
Hi,
Try something like this:
using (Stream s = new MemoryStream()) { XmlWriterSettings ws = new XmlWriterSettings(); ws.Encoding = Encoding.Unicode; using (XmlWriter w = XmlWriter.Create(s, ws)) { xmlserializer.Serialize(w, myobject); } }
Note that you must use XmlWriter over a Stream. Using it over either StringBuilder or TextWriter will not produce the BOM, as those classes use the UTF-16 as default and the BOM can't be represented in them. The writer will produce the BOM automatically when create over Stream.
Thanks,
这篇关于XML Serializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!