Qt中使用DOM解析XML文件或者字符串(实例)
2023-09-11 14:16:38 时间
因为需要读取配置文件,我的配置文件采用xml;因此编写了使用qt读取xml文件内容的代码,xml文件
如下:
- <?xml version="1.0" encoding="UTF-8" ?>
- <configuration>
- <server>
- <item key="serverip" value="222.88.1.146" />
- <item key="serverport" value="5000" />
- </server>
- </configuration>
为了读取xml,我编写ReadConfig类代码如下:
ReadConfig.h文件内容如下
- /******************************************************************************
- *
- * 文件名: ReadConfig.h
- *
- * 文件摘要: 读取系统配置文件
- *
- * 作者:程晓鹏
- *
- * 文件创建时间: 2012/02/23 09:59:36
- *
- *******************************************************************************/
- #ifndef READCONFIG_H
- #define READCONFIG_H
- #include <QString>
- #include <QFile>
- #include <QDomDocument>
- /**
- * 读取配置文件类
- *
- */
- class ReadConfig{
- public:
- /**
- * 构造函数
- *
- */
- ReadConfig();
- /**
- * 析构函数
- *
- */
- ~ReadConfig();
- /**
- * 获取配置文件中的值
- *
- * @param key 配置的键
- * @param type 类型标签
- *
- * @return 配置项对应的值
- */
- QString getValue(const QString &key, const QString &type = "server");
- private:
- QFile *localfile;
- QDomDocument *dom;
- };
- #endif
ReadConfig.cpp内容如下:
- /******************************************************************************
- *
- * 文件名: ReadConfig.cpp
- *
- * 文件摘要: ReadConfig.h的实现文件
- *
- * 作者:程晓鹏
- *
- * 文件创建时间: 2012/02/23 10:07:05
- *
- *******************************************************************************/
- #include "ReadConfig.h"
- ReadConfig::ReadConfig()
- {
- QString strfilename = QString("p2p.config");
- localfile = new QFile(strfilename);
- if(!localfile->open(QFile::ReadOnly)){
- return;
- }
- dom = new QDomDocument();
- if(!dom->setContent(localfile)){
- localfile->close();
- return;
- }
- }
- ReadConfig::~ReadConfig()
- {
- delete localfile;
- localfile = 0;
- delete dom;
- dom = 0;
- }
- QString ReadConfig::getValue(const QString &key, const QString &type)
- {
- QString result = "";
- QDomNodeList nodelist = dom->elementsByTagName(type); /**< 读取类型节点集合 */
- for(int i=0; i<nodelist.count(); i++){
- QDomNode node = nodelist.at(i);
- QDomNodeList itemlist = node.childNodes(); /**< 获取字节点集合 */
- for(int j=0; j<itemlist.count(); j++){
- QDomNode mynode = itemlist.at(j);
- if(mynode.toElement().attribute("key") == key){ /**< 查找所需要的键值 */
- result = mynode.toElement().attribute("value");
- break;
- }
- }
- }
- return result;
- }
另外,因为采用Qt的xml模块,记得在你的项目pro文件中添加对xml的引用
QT += xml
相关文章
- Qt-Qt使用QWebsocket实现服务端和客户端通信
- QT-Qt图片按钮类
- QT-Qt组件QTimer使用方法
- Qt-char*与QString互转 floatToqstring char*与QString互转 qt字符串与字符串数组操作 Qt 的QString类的使用
- CentOS下Qt安装
- 分析21个 Qt隐藏功能和技巧
- s3c2410上搭建QT/Embedded4.8.5开发环境(七)--命令行开始第一个Qt程序
- Qt编写自定义控件32-等待进度条控件
- Qt Windows 环境搭建
- Qt QML和QtQuick简介以及QML实例
- Qt中的Q_D宏和d指针
- Qt Plugin插件机制与实例
- Qt多线程编程实例
- Qt 之图形(QPainter 的基本绘图)
- 【Qt】在ubuntu上为可执行程序qt创建图标(亲测)
- 9、QT基础——Qt消息机制和事件
- 2、QT基础——创建Qt项目
- 1、QT基础——Qt概述
- qt之捕获全局事件
- QT QSplashScreen程序启动画面使用心得
- Qt creator 编译错误 :cannot find file .pro qt
- Qt 界面使用自己定义控件 "提升为"
- Qt 中QString 字符串操作:连接、组合、替换、去掉空白字符