以本人这篇博文的源码为例:
https://blog.csdn.net/qq78442761/article/details/80501909
源码改成如下所示:
#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QVector>
#include <QXmlStreamReader>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile file("C:\\Users\\Administrator\\Desktop\\DrawPic\\1.dat");
if(!file.open(QFile::ReadOnly|QFile::Text)){
qDebug()<<"读取XML文件时,文件打开失败";
return false;
}
QXmlStreamReader reader;
reader.setDevice(&file);
while(!reader.atEnd()){
reader.readNext();
qDebug()<<reader.text();
}
file.close();
return a.exec();
}
xml文件就是这样的
<test>
<data1>
<name1>你妹</name1>
<name2>你妹妹</name2>
<name3>你妹妹妹</name3>
<name4>你妹妹妹妹</name4>
<name5>你妹妹妹妹妹</name5>
<double>3.1415</double>
<int1>10</int1>
<attribution include="100">
<int3>1000</int3>
</attribution>
</data1>
<data2>
<name1>你姐</name1>
<name2>你姐姐</name2>
<name3>你姐姐姐</name3>
<name4>你姐姐姐姐</name4>
<name5>你姐姐姐姐姐</name5>
<double>6.6666</double>
<int1>66</int1>
<attribution include="666">
<int3>66666</int3>
</attribution>
</data2>
</test>
把这个编码改成ANSI编码存储,如下图所示:
<?xml version="1.0" encoding="GBK"?>
这一行是去掉了的,
此时是读不了数据的,因为Qt Creator 默认采用UTF-8编码,而setCodec这个函数在QXmlStreamReader中并没有,所有读不了。
对于这个坑有以下几个方法:
1.修改程序字符编码;
2.加上encoding,让QXmlStreamReader知道应该采用咋样的编码;
3.保存文件的时候,采用UTF-8的格式存储