环境是VS2008,.Net 3.5
以下C#代码(注意UTF8的指定编码)
XmlWriterSettings settings = new XmlWriterSettings (); StringBuilder sb = new StringBuilder(); settings.Encoding = System.Text.Encoding.UTF8; settings.Indent = false; settings.NewLineChars = "\n"; settings.ConformanceLevel = System.Xml.ConformanceLevel.Document; XmlWriter writer = XmlWriter.Create (sb, settings); { // Write XML data. writer.WriteStartElement ("CCHEADER"); writer.WriteAttributeString ("ProtocolVersion", "1.0.0"); writer.WriteAttributeString ("ServerCapabilities", "0x0000000F"); writer.WriteEndElement (); writer.Flush (); }
实际上生成XML(> <省略,因为它们上面有SO barfs):
?xml version ="1.0"encoding ="utf-16"?
CCHEADER ProtocolVersion ="1.0.0"ServerCapabilities ="0x0000000F"/
为什么我在这里生成了错误的编码?我究竟做错了什么 ?
我怀疑这是因为它正在写一个StringBuilder,它本身就是UTF-16.另一种方法是创建一个派生自StringWriter的类,但它会覆盖Encoding属性.
我相信我在MiscUtil中有一个- 但无论如何写它都是微不足道的.像这样的东西:
public sealed class StringWriterWithEncoding : StringWriter { private readonly Encoding encoding; public StringWriterWithEncoding (Encoding encoding) { this.encoding = encoding; } public override Encoding Encoding { get { return encoding; } } }