因为需要读取配置文件,我的配置文件采用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