当前位置:网站首页>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
边栏推荐
- 【解释】get ORA-12838: cannot read/modify an object after modifying it in parallel
- LeetCoed18. Sum of four numbers
- An idea plug-in that doesn't work, but can install X
- js将树形结构数据转为一维数组数据
- 扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...
- 编译原理题-带答案
- Qt读取路径下所有文件或指定类型文件(含递归、判断是否为空、创建路径)
- LeetCode简单题之计算字符串的数字和
- 数论求a^b(a,b为1e12级别)的因子之和
- Compiling principle questions - with answers
猜你喜欢
ansible自動化運維詳解(一)ansible的安裝部署、參數使用、清單管理、配置文件參數及用戶級ansible操作環境構建
通过实现参数解析器HandlerMethodArgumentResolver接口来自定义注解
Positioning of high precision welding manipulator
stm32以及freertos 堆栈解析
Search the complete navigation program source code
分布式消息中间件框架选型-数字化架构设计(7)
Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结
AAAI 2022招募讲者啦!!
干货!以点为形:可微分的泊松求解器
The annotation is self-defined by implementing the parameter parser handlermethodargumentresolver interface
随机推荐
编译原理题-带答案
Online app resource download website source code
Install MySQL for Ubuntu and query the average score
为什么会存在1px问题?怎么解决?
The third divisor of leetcode simple question
浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda
欧圣电气深交所上市:市值52亿 陆为东父女为美国籍
Samsung, March to the west again
Qt读取路径下所有文件或指定类型文件(含递归、判断是否为空、创建路径)
LeetCode简单题之三除数
Compiling principle questions - with answers
ansible自動化運維詳解(一)ansible的安裝部署、參數使用、清單管理、配置文件參數及用戶級ansible操作環境構建
Kubernetes in browser and IDE | interactive learning platform killercoda
Brief description of CPU
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
Ansible Automation Operation and Maintenance details (ⅰ) Installation and Deployment, Parameter use, list Management, Profile Parameters and user level ansible operating environment Construction
校园转转二手市场源码下载
一个没啥L用,但可以装X的IDEA插件
LeetCode简单题之计算字符串的数字和
Planification du mouvement du manipulateur dans l'assemblage 3c