背景:如果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)) ;
}