c#读写xml的例子网上很多,也很简单,但在实际的运用过程中却发现有许多的困难。之前操作的xml文件一般都是自己定义的。通常的写法就是:
XmlDocument doc = new XmlDocument();
string path = "config.xml";
doc.Load(path);
//xml读取操作
doc.Save(path);
这通常是没有问题的,但是,如果编码格式不对就会报错:给定编码中的字符无效!
就比如我的这个xml文件,一般xml文件头都会标记出编码格式,但有的只有这么一行:
<?xml version='1.0' standalone='yes' ?>
那么到底该怎么读取特定编码格式的xml文件呢,同时我们应该怎么确定xml文件的编码格式。
这里,我用的是NotePad++编辑器,我也是偶然间发现它能识别文件的编码格式,一般学编程的朋友都会使用它,还么有下载的朋友可以get起来啦。我们使用这个软件打开xml文件,在底部就会看到文件的编码格式:
知道了编码格式我们就可操作了,具体方法如下:
XmlDocument doc = new XmlDocument();
string path = "config.xml";
using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("GB2312")))
{
doc.Load(reader);//使用数据流读取可以确定读取编码格式
}
//doc.Load(path);
//xml读取操作
doc.Save("config1.xml");
这样,读取就没什么问题了,但是,当打开保存的文件,却发现编码格式变了,这肯定是不行的,不可能每次打开都要切换读取的编码格式,而且很多时候保存的文件会出现乱码等问题:
原因是save方法默认保存为UTF-8格式,所以在进行写入的时候也应该确定编码格式,同样是使用数据流,具体方法:
XmlDocument doc = new XmlDocument();
string path = "config.xml";
using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("GB2312")))
{
doc.Load(reader);//使用数据流读取可以确定读取编码格式
}
//doc.Load(path);
//xml读取操作
// doc.Save("config1.xml");
using (StreamWriter sw = new StreamWriter("config1.xml", false, Encoding.GetEncoding("GB2312")))
{
doc.Save(sw);
};
运行结果:
保存的格式达到目的,而且不会出现乱码。