******************************************************************************
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>
"Name" : "zhangsan"
"Age" : "12"
"Course" : "10090"
--- "Math" : "100"
--- "Chinese" : "90"