TinyXML应用例子

开发软件时经常需要把一些东西做成可配置的,于是就需要用到配置文件,以前多是用ini文件,然后自己写个类来解析。现在有了XML,许多应用软件就喜欢把配置文件做成XML格式。但是如果我们的程序本身很小,为了读取个配置文件却去用Xerces XML之类的库,恐怕会得不偿失。那么用TinyXML吧,它很小,只有六个文件,加到项目中就可以开始我们的配置文件之旅了。

前些时候我恰好就用TinyXML写了一个比较通用的配置文件类,基本可以适应大部分的场合,不过配置文件只支持两层结构,如果需要支持多层嵌套结构,那还需要稍加扩展一下。

从下面的源代码中,你也可以看到怎么去使用TinyXML,也算是它的一个应用例子了。

/*
**FileName:config.h
**Author:hansen
**Date:May11,2007
**Comment:配置文件类,主要用来读取xml配置文件中的一些配置信息
*/


#ifndef_CONFIG
#define_CONFIG

#include<string>
#include"tinyxml.h"

usingnamespacestd;

classCConfig
{
public:
explicitCConfig(constchar*xmlFileName)
:mXmlConfigFile(xmlFileName),mRootElem(0)
{
//加载配置文件
mXmlConfigFile.LoadFile();

//得到配置文件的根结点
mRootElem=mXmlConfigFile.RootElement();
}

public:
//得到nodeName结点的值
stringGetValue(conststring&nodeName);

private:
//禁止默认构造函数被调用
CMmsConfig();

private:
TiXmlDocumentmXmlConfigFile;
TiXmlElement*mRootElem;

};

#endif

/*
**FileName:config.cpp
**Author:hansen
**Date:May11,2007
**Comment:
*/


#include"config.h"
#include<iostream>

stringCConfig::GetValue(conststring&nodeName)
{
if(!mRootElem)
{
cout<<"读取根结点出错"<<endl;
return"";
}

TiXmlElement*pElem=mRootElem->FirstChildElement(nodeName.c_str());
if(!pElem)
{
cout<<"读取"<<nodeName<<"结点出错"<<endl;
return"";
}

returnpElem->GetText();

}


intmain()
{
CConfigxmlConfig("XmlConfig.xml");

//获取Author的值
stringauthor=xmlConfig.GetValue("Author");
cout<<"Author:"<<author<<endl;

//获取Site的值
stringsite=xmlConfig.GetValue("Site");
cout<<"Site:"<<site<<endl;

//获取Desc的值
stringdesc=xmlConfig.GetValue("Desc");
cout<<"Desc:"<<desc<<endl;

return0;
}

假设配置文件是这样的:

<!–XmlConfig.xml–>
<?xmlversion="1.0"encoding="GB2312"?>
<Config>
<Author>hansen</Author>
<Site>www.hansencode.cn</Site>
<Desc>这是个测试程序</Desc>
</Config>

怎么使用上面的配置类来读取XmlConfig.xml文件中的配置呢?很简单:

intmain()
{
CConfigxmlConfig("XmlConfig.xml");

//获取Author的值
stringauthor=xmlConfig.GetValue("Author");
cout<<"Author:"<<author<<endl;

//获取Site的值
stringsite=xmlConfig.GetValue("Site");
cout<<"Site:"<<site<<endl;

//获取Desc的值
stringdesc=xmlConfig.GetValue("Desc");
cout<<"Desc:"<<desc<<endl;

return0;
}

运行结果如下:

D:\config\Debug>config.exe Author:hansen Site:www.hansencode.cn Desc:这是个测试程序

相关文章

xml怎么加入图片路径
rss源错误怎么解决
文件后缀xml是什么意思
xml格式电子发票怎么获取
xml格式是什么意思
rss是什么意思啊