博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

TinyXML应用例子

Posted on 2011-04-10 21:49  tianya10319  阅读(319)  评论(0编辑  收藏  举报
转载:http://wihate.blog.163.com/blog/static/2092267200711246245163/ 
开发软件时经常需要把一些东西做成可配置的,于是就需要用到配置文件,以前多是用ini文件,然后自己写个类来解析。现在有了XML,许多应用软件就喜欢把配置文件做成XML格式。但是如果我们的程序本身很小,为了读取个配置文件却去用Xerces XML之类的库,恐怕会得不偿失。那么用TinyXML吧,它很小,只有六个文件,加到项目中就可以开始我们的配置文件之旅了。

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

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

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

#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:这是个测试程序