生成XML的一种方法如下:
using System.Xml; private void SaveXML(string savePath) { XmlWriterSettings setting = new XmlWriterSettings(); setting.Indent = true; setting.NewLineOnAttributes = false; using (XmlWriter writer = XmlWriter.Create(savePath, setting)) { writer.WriteStartDocument(); writer.WriteStartElement("Config"); writer.WriteStartElement("First"); writer.WriteAttributeString("ID","1"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); } }
此时生成的XML是带BOM的UTF8编码。
带BOM的UTF8编码方式下,一个中文占2个字节;不带BOM的UTF8编码方式下,一个中文占3个字节。
若要生成不带BOM的UTF8格式,添加一行代码即可。
using System.Xml; private void SaveXML(string savePath) { XmlWriterSettings setting = new XmlWriterSettings(); setting.Indent = true; setting.NewLineOnAttributes = false; setting.Encoding = new UTF8Encoding(false); using (XmlWriter writer = XmlWriter.Create(savePath, setting)) { writer.WriteStartDocument(); writer.WriteStartElement("Config"); writer.WriteStartElement("First"); writer.WriteAttributeString("ID","1"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); } }