在项目开发过程中,发现经常遇见一些比如XML、INI、JSON等文件的读写,这里对这些文件进行整理和汇总,并展示一个简单的demo来实现上述文件的读写,以便大家学习,如有错误之处,欢迎大家批评指正。
提示:以下是本篇文章正文内容,下面案例可供参考
XML是可扩展标记语言,是一种通用的文本格式,被广泛运用于数据交换和数据存储,也可以用作配置文件。
在Qt中有三种方式来进行xml文件的读取:
1.使用XML流,读:QXmlStreamReader 写:QXmlStreamWriter
2.使用DOM读写
3.SAX为XML解析器提供了一个基于事件的标准接口
其中本文示例中使用的是第一种方式来进行读写,需要包含以下头文件,具体实现方式可看下文完整代码
//xml
#include
#include
#include
INI文件即初始化文件,通常存放的是一个程序的初始化信息,常用来做配置文件,其结构比较简单,由节、键、值组成,比较容易操作。
在Qt中可以使用QSettings类来进行ini文件的读写,需要包含以下头文件,具体实现方式可看下文完整代码
//ini
#include
JSON是一种轻量级的数据交换格式,它基于JavaScript的一个子集,易于人的编写和阅读,也易于机器解析,json 文件由对象和数组组成。
本文的demo中读写的json文件比较简单,只有对象,但是在使用到数组的情况下需要包含以下头文件,具体实现方式可看下文完整代码
//json
#include //对象
#include //数组
#include
1.widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
//xml
#include
#include
#include
//ini
#include
//json
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
typedef struct person
{
QString name;
QString gender;
int age;
double height;
double weight;
}PersonData;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void xmlFlieRead();
bool xmlFileWrite();
void iniFileRead();
bool iniFileWrite();
void jsonFileRead();
bool jsonFileWrite();
void setFileValue(QString fileType);
void showFileValue(QString fileType);
private slots:
void on_pb_xmlRead_clicked();
void on_pb_xmlWrite_clicked();
void on_pb_iniRead_clicked();
void on_pb_iniWrite_clicked();
void on_pb_jsonRead_clicked();
void on_pb_jsonWrite_clicked();
private:
Ui::Widget *ui;
PersonData xmlData;
PersonData iniData;
PersonData jsonData;
};
#endif // WIDGET_H
2.widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->xmlFlieRead(); //初始化读取xml文件
}
Widget::~Widget()
{
delete ui;
}
void Widget::xmlFlieRead()
{
QString xmlFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/xmlFile.xml";
QFile file(xmlFile);
if(!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::warning(this,"警告","xml文件打开失败!");
return;
}
QXmlStreamReader xmlRead;
xmlRead.setDevice(&file);
if(xmlRead.readNextStartElement()) //读取root
{
if(xmlRead.name().toString() == "root")
{
if(xmlRead.readNextStartElement()) //读取config
{
if(xmlRead.name().toString() == "config")
{
while(xmlRead.readNextStartElement()) //循环读取Item
{
if(xmlRead.name().toString() == "Item")
{
QXmlStreamAttributes attributes = xmlRead.attributes();
if(attributes.hasAttribute("Name"))
{
QString s_name = attributes.value("Name").toString();
//qDebug()<<"s_name:"<
if(s_name == "name")
{
xmlData.name = xmlRead.readElementText();
}
else if(s_name == "gender")
{
xmlData.gender = xmlRead.readElementText();
}
else if(s_name == "age")
{
xmlData.age = xmlRead.readElementText().toInt();
}
else if(s_name == "height")
{
xmlData.height = xmlRead.readElementText().toDouble();
}
else if(s_name == "weight")
{
xmlData.weight = xmlRead.readElementText().toDouble();
}
else
{
qDebug()<<"readItem error";
xmlRead.readNextStartElement();
}
}
}
}
}
}
}
}
//更新界面
showFileValue("xml");
}
bool Widget::xmlFileWrite()
{
QString xmlFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/xmlFile.xml";
QFile file(xmlFile);
if(!file.open(QFile::WriteOnly | QFile::Text | QFile :: Truncate))
{
return false;
}
QXmlStreamWriter xmlWrite(&file);
xmlWrite.setAutoFormatting(true);
xmlWrite.writeStartDocument("1.0",true);
xmlWrite.writeStartElement("root");
xmlWrite.writeStartElement("config");
xmlWrite.writeAttribute("filename","xmlFile.xml");
xmlWrite.writeStartElement ("Item");
xmlWrite.writeAttribute("Name","name");
xmlWrite.writeAttribute("Type","string");
xmlWrite.writeAttribute("Note","姓名");
xmlWrite.writeCharacters(xmlData.name);
xmlWrite.writeEndElement();
xmlWrite.writeStartElement ("Item");
xmlWrite.writeAttribute("Name","gender");
xmlWrite.writeAttribute("Type","string");
xmlWrite.writeAttribute("Note","性别");
xmlWrite.writeCharacters(xmlData.gender);
xmlWrite.writeEndElement();
xmlWrite.writeStartElement ("Item");
xmlWrite.writeAttribute("Name","age");
xmlWrite.writeAttribute("Type","int");
xmlWrite.writeAttribute("Note","年龄");
xmlWrite.writeCharacters(QString::number(xmlData.age));
xmlWrite.writeEndElement();
xmlWrite.writeStartElement ("Item");
xmlWrite.writeAttribute("Name","height");
xmlWrite.writeAttribute("Type","double");
xmlWrite.writeAttribute("Note","身高");
xmlWrite.writeCharacters(QString::number(xmlData.height));
xmlWrite.writeEndElement();
xmlWrite.writeStartElement ("Item");
xmlWrite.writeAttribute("Name","weight");
xmlWrite.writeAttribute("Type","double");
xmlWrite.writeAttribute("Note","体重");
xmlWrite.writeCharacters(QString::number(xmlData.weight));
xmlWrite.writeEndElement();
xmlWrite.writeEndElement(); //config结束
xmlWrite.writeEndElement(); //root结束
xmlWrite.writeEndDocument(); //Document结束
file.close();
return true;
}
void Widget::iniFileRead()
{
QString iniFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/iniFile.ini";
QSettings iniRead(iniFile,QSettings::IniFormat);
iniRead.setIniCodec("UTF-8"); //注意编码
iniRead.beginGroup("VALUE");
iniData.name = iniRead.value("name").toString();
iniData.gender = iniRead.value("gender").toString();
iniData.age = iniRead.value("age").toInt();
iniData.height = iniRead.value("height").toDouble();
iniData.weight = iniRead.value("weight").toDouble();
iniRead.endGroup();
//更新界面
showFileValue("ini");
}
bool Widget::iniFileWrite()
{
QString iniFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/iniFile.ini";
QSettings iniWrite(iniFile,QSettings::IniFormat);
iniWrite.setIniCodec("UTF-8"); //注意编码,解决中文字符乱码
iniWrite.beginGroup("VALUE");
iniWrite.setValue("name",iniData.name);
iniWrite.setValue("gender",iniData.gender);
iniWrite.setValue("age",iniData.age);
iniWrite.setValue("height",iniData.height);
iniWrite.setValue("weight",iniData.weight);
iniWrite.endGroup();
return true;
}
void Widget::jsonFileRead()
{
QString jsonFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/jsonFile.json";
QFile file(jsonFile);
if(!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this,"警告","json文件打开失败!");
return;
}
QByteArray data(file.readAll());
file.close();
QJsonParseError jError;
QJsonDocument jDoc = QJsonDocument::fromJson(data,&jError);
if(jError.error != QJsonParseError::NoError)
{
QMessageBox::critical(this,"错误","json文件错误!");
return;
}
QJsonObject mainObject = jDoc.object();
{
jsonData.name = mainObject["name"].toString();
jsonData.gender = mainObject["gender"].toString();
jsonData.age = mainObject["age"].toInt();
jsonData.height = mainObject["height"].toDouble();
jsonData.weight = mainObject["weight"].toDouble();
}
//更新界面
showFileValue("json");
}
bool Widget::jsonFileWrite()
{
QJsonObject mainObject; //读写比较复杂的json文件,可以使用大括号来方便区分
{
mainObject.insert("name",jsonData.name);
mainObject.insert("gender",jsonData.gender);
mainObject.insert("age",jsonData.age);
mainObject.insert("height",jsonData.height);
mainObject.insert("weight",jsonData.weight);
}
QJsonDocument jDoc(mainObject);
QString jsonFile = "D:/QT/Project/my_Project/18_FileReadWrite/TestFile/jsonFile.json";
QFile file(jsonFile);
if(!file.open(QIODevice::WriteOnly))
{
return false;
}
QByteArray data(jDoc.toJson());
file.write(data);
file.close();
return true;
}
void Widget::setFileValue(QString fileType)
{
if(fileType == "xml")
{
xmlData.name = ui->le_name->text();
xmlData.gender = ui->cb_gender->currentText();
xmlData.age = ui->le_age->text().toInt();
xmlData.height = ui->le_height->text().toDouble();
xmlData.weight = ui->le_weight->text().toDouble();
}
else if(fileType == "ini")
{
iniData.name = ui->le_name->text();
iniData.gender = ui->cb_gender->currentText();
iniData.age = ui->le_age->text().toInt();
iniData.height = ui->le_height->text().toDouble();
iniData.weight = ui->le_weight->text().toDouble();
}
else if(fileType == "json")
{
jsonData.name = ui->le_name->text();
jsonData.gender = ui->cb_gender->currentText();
jsonData.age = ui->le_age->text().toInt();
jsonData.height = ui->le_height->text().toDouble();
jsonData.weight = ui->le_weight->text().toDouble();
}
}
void Widget::showFileValue(QString fileType)
{
if(fileType == "xml")
{
ui->le_name->setText(xmlData.name);
if(xmlData.gender == "男")
{
ui->cb_gender->setCurrentIndex(0);
}
else if(xmlData.gender == "女")
{
ui->cb_gender->setCurrentIndex(1);
}
else
{
ui->cb_gender->setCurrentIndex(0);
}
ui->le_age->setText(QString::number(xmlData.age));
ui->le_height->setText(QString::number(xmlData.height));
ui->le_weight->setText(QString::number(xmlData.weight));
}
else if(fileType == "ini")
{
ui->le_name->setText(iniData.name);
if(iniData.gender == "男")
{
ui->cb_gender->setCurrentIndex(0);
}
else
{
ui->cb_gender->setCurrentIndex(1);
}
ui->le_age->setText(QString::number(iniData.age));
ui->le_height->setText(QString::number(iniData.height));
ui->le_weight->setText(QString::number(iniData.weight));
}
else if(fileType == "json")
{
ui->le_name->setText(jsonData.name);
if(jsonData.gender == "男")
{
ui->cb_gender->setCurrentIndex(0);
}
else
{
ui->cb_gender->setCurrentIndex(1);
}
ui->le_age->setText(QString::number(jsonData.age));
ui->le_height->setText(QString::number(jsonData.height));
ui->le_weight->setText(QString::number(jsonData.weight));
}
}
void Widget::on_pb_xmlRead_clicked()
{
xmlFlieRead();
}
void Widget::on_pb_xmlWrite_clicked()
{
setFileValue("xml");
if(xmlFileWrite())
{
QMessageBox::information(this,"提示","xml文件保存成功!");
}
}
void Widget::on_pb_iniRead_clicked()
{
iniFileRead();
}
void Widget::on_pb_iniWrite_clicked()
{
setFileValue("ini");
if(iniFileWrite())
{
QMessageBox::information(this,"提示","ini文件保存成功!");
}
}
void Widget::on_pb_jsonRead_clicked()
{
jsonFileRead();
}
void Widget::on_pb_jsonWrite_clicked()
{
setFileValue("json");
if(jsonFileWrite())
{
QMessageBox::information(this,"提示","json文件保存成功!");
}
}
我的示例百度网盘链接:https://pan.baidu.com/s/1M1Flq0-1lj4A5KV3sRdLUw
提取码:xxcj
可以看到本文demo中所进行读写的几个文件都是比较简单的,内容比较少并且结构也比较简易,这里也只是为大家展示基本的读写方法。但是在实际的开发过程中,文件内容会存在循环,嵌套等等的复杂结构,对于相关的文件大家可以查看文末的参考文章。在我们的开发过程中需要注意观察,其实这几种类型的文件读写都是比较简单的,本质上都是获取参数,进行文件写,读取参数,界面显示读到的参数。另外在实际开发中,建议先进行写文件,再然后读,这样感觉开发起来简单(哈哈这是我自己的感jio~~~)。
hello:
共同学习,共同进步,如果还有相关问题,可在评论区留言进行讨论。
参考文章:
QT中读取XML文件三种方式的实例
Qt读写ini文件
JSON简介
Qt 操作Json格式文件(创建、插入、解析、修改、删除)