当前位置:网站首页>QT reading and writing XML files
QT reading and writing XML files
2022-04-23 08:19:00 【Ott_ Glodon】
One 、 brief introduction
Use XML modular , stay .pro Add... To the file QT += xml , And add the corresponding header file
#include
#include perhaps #include .
QtXml Module provides a read and write XML The flow of documents , The parsing method includes DOM and SAX.
(1)DOM(Document ObjectModel): take XML The file is represented as a tree , Facilitate random access to the nodes , But it consumes relatively more memory .
(2)SAX(Simple APIfor XML): An event driven XML API, Close to the bottom , Faster , But it is not convenient for random access to any node .
Two 、QDomDocument Read and write files
1、 Read xml file
Read a xml file , adopt QtTree Control is displayed , The effect is as follows :
testXML.xml The original document
<?xml version="1.0" encoding="UTF-8"?>
<class type="school">
< name >testXML</ name >
< Address >
< Province > Shanxi Province </ Province >
< City > Taiyuan City </ City >
< District > Small store area </ District >
</ Address >
< School >
< name > Taiyuan No.1 Middle School </ name >
< Category > Senior high school </ Category >
</ School >
< In grade one >
< Class one >
< The number of >24</ The number of >
< The male to female ratio >1:2</ The male to female ratio >
</ Class one >
< Class two >
< The number of >25</ The number of >
< The male to female ratio >3:2</ The male to female ratio >
</ Class two >
< Class three >
< The number of >25</ The number of >
< The male to female ratio >2:3</ The male to female ratio >
</ Class three >
</ In grade one >
</class>

1、 Read xml
// Select File
void Dialog::on_pushBtn_open_clicked()
{
QString sFileName = QFileDialog::getOpenFileName(this," choice XML file ","/","xml files(*.xml)");
// Judge whether the file exists
QFile fileName(sFileName);
if(!fileName.exists())
{
return;
}
ReadXMLFile(sFileName);
}
// Select the file and open
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();
}
// Read recursively xml Content and display it in the tree control
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、 Write generation xml
Generate xml file , The effect is as follows :

The code is as follows :
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( " name " );
text = doc.createTextNode( "testXML" );
element.appendChild(text);
root.appendChild(element);
element = doc.createElement( " Address " );
QDomElement childElement = doc.createElement( " Province " );
text = doc.createTextNode( " Shanxi Province " );
childElement.appendChild(text);
element.appendChild(childElement);
childElement = doc.createElement( " City " );
text = doc.createTextNode( " Taiyuan City " );
childElement.appendChild(text);
element.appendChild(childElement);
root.appendChild(element);
doc.save(out, 4); //each line space of file is 4
return 0;
}
版权声明
本文为[Ott_ Glodon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230714487299.html
边栏推荐
- 通过实现参数解析器HandlerMethodArgumentResolver接口来自定义注解
- 英语课小记(四)
- Find the largest of 3 strings (no more than 20 characters per string).
- 基于TCP/IP协议的网络通信实例——文件传输
- MySQL数据库中delete、truncate、drop原理详解
- [Effective Go 中文翻译]函数篇
- 3C裝配中的機械臂運動規劃
- js将树形结构数据转为一维数组数据
- Smart business card applet business card details page function implementation key code
- 网赚APP资源下载类网站源码
猜你喜欢

Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结

LeetCode中等题之旋转函数

Positioning of high precision welding manipulator

【学习】从零开始的音视频开发(9)——NuPlayer

扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...

在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)

396. Rotate Function
![[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test](/img/4a/c741ec4f9aa724e150a5ae24d0f9e9.png)
[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test

dried food! Point based: differentiable Poisson solver

thinkphp6+jwt 实现登录验证
随机推荐
Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结
如何保护开源项目免遭供应链攻击-安全设计(1)
Listed on the Shenzhen Stock Exchange: the market value is 5.2 billion yuan. Lu is the East and his daughter is American
Find the largest of 3 strings (no more than 20 characters per string).
多目视觉SLAM
LeetCode简单题之计算字符串的数字和
php生成短链接:将数字转成字母,将字母转成数字
Situational leaders - Chapter 7, solving performance problems
colorui 解决底部导航遮挡内容问题
396. Rotate Function
分布式消息中间件框架选型-数字化架构设计(7)
Online app resource download website source code
Compiling principle questions - with answers
如何在SQL Server中导入excel数据,2019版
Somme numérique de la chaîne de calcul pour un problème simple de leetcode
js将树形结构数据转为一维数组数据
編譯原理題-帶答案
AAAI 2022 recruit speakers!!
Community group purchase applet source code + interface DIY + nearby leader + supplier + group collage + recipe + second kill + pre-sale + distribution + live broadcast
华硕笔记本电脑重装系统后不能读取usb,不能上网