冬眠
“如果你觉得自己在为傻瓜设计产品,那么很可能不仅无法设计出优秀的产品,而且连傻瓜也不喜欢你的设计。”--Paul Graham

导航

 

生成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();
    }
}

 

posted on 2013-12-30 17:33  无尽的冬眠  阅读(1577)  评论(0编辑  收藏  举报