tinyxml对xml简单的读写操作

背景:如果xml配置文件存在,直接读取配置,如果不存在需要创建一个xml文件,写入默认的配置的配置。

判断xml是否存在

#define CONFIG_FILE "conf.xml"
void Config::initConfig()
{
    if(access(CONFIG_FILE, F_OK) != F_OK)
    {
       createFile();
    }else
    {
        readConfigFile();
    }
}

创建xml文件

#define CONFIG_FILE "conf.xml"
#define ROOT_ELEMENT "MyCase"
#define CONTROL "controlInfo"
#define STATION "station"
#define TSIP "ip"
#define TSPORT "port"

std::string controlIp ;
int controlPort ;
std::string stationIp ;
int stationPort ;

void Config::createFile()
{
    TiXmlDocument doc(CONFIG_FILE);     //创建一个文档类
    TiXmlDeclaration* dec = new TiXmlDeclaration("1.0","",""); //创建一个描述,构造参数(version,encoding,standalone)

    TiXmlElement* rootElement = new TiXmlElement(ROOT_ELEMENT);      //创建一个根element root
    doc.LinkEndChild(dec);//文档添加描述
    doc.LinkEndChild(rootElement);//文档添加root element
 
    TiXmlElement *con = new TiXmlElement(CONTROL);
    con->SetAttribute(TSIP , controlIp.c_str());
    con->SetAttribute(TSPORT , controlPort);
    rootElement->LinkEndChild(con) ;

    TiXmlElement *station = new TiXmlElement(STATION);
    station->SetAttribute(TSIP , stationIp.c_str());
    station->SetAttribute(TSPORT , stationPort);
    rootElement->LinkEndChild(station) ;

    doc.SaveFile(CONFIG_FILE);//保存到文件new.xml
}

读取配置文件

void Config::readConfigFile()
{
    TiXmlDocument doc(CONFIG_FILE);
    bool loadOk=doc.LoadFile();//加载文档
    if(!loadOk)
    {
        std::cout<<"could not load the test file.Error:"<<doc.ErrorDesc()<<"\n";
        return ;
    }

    TiXmlElement *RootElement=doc.RootElement();	//根元素, Info
    if(RootElement == NULL)
        return ;
   // cout<< "[root name]" << RootElement->Value() <<"\n";
   TiXmlElement* con = RootElement->FirstChildElement(CONTROL);
   if(con == NULL)
       return ;
   controlIp = con->Attribute(TSIP) ;
   controlPort = atoi(con->Attribute(TSPORT)) ;

   TiXmlElement* station = RootElement->FirstChildElement(STATION);
   if(station == NULL)
       return ;
   controlIp = station->Attribute(TSIP) ;
   controlPort = atoi(station->Attribute(TSPORT)) ;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值