1. 程式人生 > >tinyxml對xml簡單的讀寫操作

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)) ;
}