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