目前虽然还不支持/CONFIG/****等多层次的直接检索,但优点是简单方便,不需要学习复杂的SDK,示例代码如下:
#ifndef _CONFIG
#define _CONFIG
#include <string>
#include "tinyxml.h"
using namespace std;
class CConfig
{
public:
explicit CConfig(const char* xmlFileName)
:mXmlConfigFile(xmlFileName),mRootElem(0)
{
//加载配置文件
mXmlConfigFile.LoadFile();
//得到配置文件的根结点
mRootElem=mXmlConfigFile.RootElement();
}
public:
//得到nodeName结点的值
string GetValue(const string& nodeName);
private:
//禁止默认构造函数被调用
CMmsConfig();
private:
TiXmlDocument mXmlConfigFile;
TiXmlElement* mRootElem;
};
#endif
/*
** FileName: config.cpp
** Author: hansen
** Date: May 11, 2007
** Comment:
*/
#include "config.h"
#include <iostream>
string CConfig::GetValue(const string& nodeName)
{
if(!mRootElem)
{
cout<<"读取根结点出错"<<endl;
return "";
}
TiXmlElement* pElem=mRootElem->FirstChildElement(nodeName.c_str());
if(!pElem)
{
cout<<"读取"<<nodeName<<"结点出错"<<endl;
return "";
}
return pElem->GetText();
}
int main()
{
CConfig xmlConfig("XmlConfig.xml");
//获取Author的值
string author = xmlConfig.GetValue("Author");
cout<<"Author:"<<author<<endl;
//获取Site的值
string site = xmlConfig.GetValue("Site");
cout<<"Site:"<<site<<endl;
//获取Desc的值
string desc = xmlConfig.GetValue("Desc");
cout<<"Desc:"<<desc<<endl;
return 0;
}
假设配置文件是这样的:
<!– XmlConfig.xml –>
<?xml version="1.0" encoding="GB2312" ?>
<Config>
<Author>hansen</Author>
<Site>www.hansencode.cn</Site>
<Desc>这是个测试程序</Desc>
</Config>
怎么使用上面的配置类来读取XmlConfig.xml文件中的配置呢?很简单:
int main()
{
CConfig xmlConfig("XmlConfig.xml");
//获取Author的值
string author = xmlConfig.GetValue("Author");
cout<<"Author:"<<author<<endl;
//获取Site的值
string site = xmlConfig.GetValue("Site");
cout<<"Site:"<<site<<endl;
//获取Desc的值
string desc = xmlConfig.GetValue("Desc");
cout<<"Desc:"<<desc<<endl;
return 0;
}
运行结果如下:
D:/config/Debug>config.exe
Author:hansen
Site:www.hansencode.cn
Desc:这是个测试程序