环境是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无法处理它们而被省略):
?xml version="1.0" encoding="utf-16"?
CCHEADER ProtocolVersion="1.0.0" ServerCapabilities="0x0000000F" /
为什么会生成错误的编码?我做错了什么?
StringWriter
专业化中让Encoding
返回null
,那么XmlWriter
将仅写入XML声明为<?xml version="1.0"?>
,即根本没有任何编码信息。这是一个完全有效的XML声明。如果我们对编码不确定,这是非常有用的。 - Jeppe Stig Nielsen