TinyXML简单应用

目前虽然还不支持/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:这是个测试程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值