当前位置:网站首页>Qt读写XML文件
Qt读写XML文件
2022-04-23 07:15:00 【欧特_Glodon】
一、简介
使用XML模块,在.pro文件中添加 QT += xml ,并加如相应的头文件
#include
#include 或者 #include 。
QtXml模块提供了一个读写XML文件的流,解析方法包含DOM和SAX。
(1)DOM(Document ObjectModel):将XML文件表示成一棵树,便于随机访问其中的节点,但消耗内存相对多一些。
(2)SAX(Simple APIfor XML):一种事件驱动的XML API,接近于底层,速度较快,但不便于随机访问任意节点。
二、QDomDocument读写文件
1、读取xml文件
读取一个xml文件,通过QtTree控件展示出来,效果如下:
testXML.xml原始文件
<?xml version="1.0" encoding="UTF-8"?>
<class type="school">
<名称>testXML</名称>
<地址>
<省份>山西省</省份>
<市>太原市</市>
<区>小店区</区>
</地址>
<学校>
<名称>太原第一中学</名称>
<类别>高级中学</类别>
</学校>
<一年级>
<一班>
<人数>24</人数>
<男女比例>1:2</男女比例>
</一班>
<二班>
<人数>25</人数>
<男女比例>3:2</男女比例>
</二班>
<三班>
<人数>25</人数>
<男女比例>2:3</男女比例>
</三班>
</一年级>
</class>

1、读取xml
// 选择文件
void Dialog::on_pushBtn_open_clicked()
{
QString sFileName = QFileDialog::getOpenFileName(this,"选择XML文件","/","xml files(*.xml)");
//判断文件是否存在
QFile fileName(sFileName);
if(!fileName.exists())
{
return;
}
ReadXMLFile(sFileName);
}
// 选择文件并打开
void Dialog::ReadXMLFile(const QString sFileName)
{
QFile file(sFileName);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument dom("TestXML");
if (dom.setContent(&file))
{
ui->treeWidget->clear();
ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
QDomElement docElem = dom.documentElement();
ShowXMLDoc(docElem, NULL);
ui->treeWidget->expandAll();
}
}
file.close();
}
// 递归读取xml内容并显示到树控件中
void Dialog::ShowXMLDoc(QDomElement &docElem, QTreeWidgetItem *pItem)
{
QDomNode node = docElem.firstChild();
if(node.toElement().isNull())
{
pItem->setText (1, docElem.text());
}
while(!node.isNull())
{
QDomElement element = node.toElement(); // try to convert the node to an element.
if( !element.isNull() )
{
QTreeWidgetItem *item;
if( pItem )
{
pItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
//pItem->setCheckState(0, Qt::Unchecked);
item = new QTreeWidgetItem(pItem);
}
else
{
item = new QTreeWidgetItem(ui->treeWidget);
}
item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
//item->setCheckState(0, Qt::Unchecked);
item->setText(0, element.tagName());
ShowXMLDoc(element, item);
if( pItem )
{
pItem->addChild(item);
}
else
{
ui->treeWidget->addTopLevelItem(item);
}
}
node = node.nextSibling();
}
return;
}
2、写入生成xml
生成xml文件,效果如下:

代码如下:
int DomDocument::writeXml()
{
QString fileName = "testXML.xml";
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
return -2;
}
QTextStream out(&file);
QDomDocument doc;
QDomText text;
QDomElement element;
QDomAttr attr;
QDomProcessingInstruction instruction;
instruction = doc.createProcessingInstruction( "xml", "version = \'1.0\' encoding=\'UTF-8\'" );
doc.appendChild( instruction );
QDomElement root = doc.createElement( "class" );
attr = doc.createAttribute( "type" );
attr.setValue("school");
root.setAttributeNode(attr);
doc.appendChild(root);
element = doc.createElement( "名称" );
text = doc.createTextNode( "testXML" );
element.appendChild(text);
root.appendChild(element);
element = doc.createElement( "地址" );
QDomElement childElement = doc.createElement( "省份" );
text = doc.createTextNode( "山西省" );
childElement.appendChild(text);
element.appendChild(childElement);
childElement = doc.createElement( "市" );
text = doc.createTextNode( "太原市" );
childElement.appendChild(text);
element.appendChild(childElement);
root.appendChild(element);
doc.save(out, 4); //each line space of file is 4
return 0;
}
版权声明
本文为[欧特_Glodon]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_37251750/article/details/124324685
边栏推荐
猜你喜欢

2022.4.11-4.17 AI行业周刊(第93期):AI行业的困局

clang 如何产生汇编文件

Somme numérique de la chaîne de calcul pour un problème simple de leetcode

The third divisor of leetcode simple question

NLLLoss+log_SoftMax=CE_Loss

Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)

LeetCode中等题之旋转函数

Go语学习笔记 - 结构体 | 从零开始Go语言

Samsung, March to the west again

vivo,硬件安全的爱与雷霆
随机推荐
Penetration test interview collection -- HVV---
nn.Module类的讲解
LeetCoed18. Sum of four numbers
idea:使用easyYapi插件导出yapi接口
[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test
Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)
dried food! Point based: differentiable Poisson solver
学fpga(从verilog到hls)
Go语学习笔记 - 结构体 | 从零开始Go语言
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
怎么读书读论文
分布式服务治理Nacos
Install MySQL for Ubuntu and query the average score
How to import Excel data in SQL server, 2019 Edition
Implementation principle of instanceof
Positioning and decoration style
clang 如何产生汇编文件
【Appium】测试时遇到手机内嵌H5页面的切换问题
CSV Column Extract列提取
PHP generates short links: convert numbers to letters and letters to numbers