******************************************************************************
QT += core gui xml
******************************************************************************
#include "mainwindow.h"
#include <QDomDocument>
#include <QTextStream>
#include <QFile>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 创建文档
QDomDocument docWrite;
// 创建根节点
QDomElement rootWrite = docWrite.createElement("Student");
// 添加根节点到文档中
docWrite.appendChild(rootWrite);
// 创建子节点并设置属性和文本内容
QDomElement name = docWrite.createElement("Name");
QDomText text = docWrite.createTextNode("zhangsan");
name.appendChild(text);
// 将子节点添加到根节点中
rootWrite.appendChild(name);
QDomElement age = docWrite.createElement("Age");
text = docWrite.createTextNode("12");
age.appendChild(text);
rootWrite.appendChild(age);
QDomElement course = docWrite.createElement("Course");
rootWrite.appendChild(course);
QDomElement math = docWrite.createElement("Math");
text = docWrite.createTextNode("100");
math.appendChild(text);
course.appendChild(math);
QDomElement chinese = docWrite.createElement("Chinese");
text = docWrite.createTextNode("90");
chinese.appendChild(text);
course.appendChild(chinese);
// 保存文档到文件
QFile fileWrite("test.xml");
if(fileWrite.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&fileWrite);
stream << docWrite.toString(4);
fileWrite.close();
}
//
QDomDocument docRead;
QFile fileRead("test.xml");
QString error = "";
int row = 0, column = 0;
if (fileRead.open(QIODevice::ReadOnly))
{
if(!docRead.setContent(&fileRead, false, &error, &row, &column))
{
qDebug() << "parse fileRead failed:" << row << "---" << column <<":" <<error;
fileRead.close();
}
else
{
fileRead.close();
QDomElement rootRead = docRead.documentElement();
QDomNode nodeRead = rootRead.firstChild();
while(!nodeRead.isNull())
{
QDomElement element = nodeRead.toElement();
if(!element.isNull())
{
qDebug() << element.tagName() << ":" << element.text();
QDomNode nodeReadSon = element.firstChild();
while(!nodeReadSon.isNull())
{
QDomElement elementSon = nodeReadSon.toElement();
if(!elementSon.isNull())
{
qDebug() << "---" << elementSon.tagName() << ":" << elementSon.text();
}
nodeReadSon = nodeReadSon.nextSibling();
}
}
nodeRead = nodeRead.nextSibling();
}
}
}
}
MainWindow::~MainWindow()
{
}
******************************************************************************
<Student>
<Name>zhangsan</Name>
<Age>12</Age>
<Course>
<Math>100</Math>
<Chinese>90</Chinese>
</Course>
</Student>文章来源:https://www.toymoban.com/news/detail-699670.html
"Name" : "zhangsan"
"Age" : "12"
"Course" : "10090"
--- "Math" : "100"
--- "Chinese" : "90"文章来源地址https://www.toymoban.com/news/detail-699670.html
到了这里,关于qt xml文件写入读取的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!