一个读取和配置XML文件的例子

1、配置文件

xml version="1.0" encoding="UTF-8" ?>
- < configs >
- < HelpFile >
  < name > hdlcnet.chm name >
  HelpFile >
- < OrderTree >
  < state > 1 state >
  OrderTree >
- < Other >
  < routetestperiod > 60 routetestperiod >
  < resetwaittime > 6 resetwaittime >
  Other >
- < DataBase >
  < type > 0 type >
  < dsn > hdlcnet dsn >
  < serverip > 192.168.0.80 serverip >
  < dbservername > SQLSERVER2005 dbservername >
  < dbname > hdlcnet dbname >
  < usrname > admin usrname >
  < usrpwd />
  DataBase >
- < Proxy >
  < uiport > 12345 uiport >
  < deviceport > 1998 deviceport >
  < almsyncperiod > 300 almsyncperiod >
  < heartbeatperiod > 30 heartbeatperiod >
  Proxy >
  configs >


2//读取某一个元素的文本
// TODO: Add your control notification handler code here
    //创建一个XML的文档对象。
    TiXmlDocument *myDocument = new TiXmlDocument("config.xml");
    myDocument->LoadFile();
    //获得根元素,即configs。
    TiXmlElement *RootElement = myDocument->RootElement();
    //输出根元素名称,即输出configs。
    char * pszRootName = (char *)RootElement->Value();
    CString strRootName = pszRootName;
    //
    TiXmlElement * element = RootElement->FirstChildElement("HelpFile")->FirstChildElement("name");
    char * pszHelpName = (char *)element->GetText();
    CString strHelpName = pszHelpName;
   
    element = RootElement->FirstChildElement("DataBase")->FirstChildElement("dbservername");
    char * pszDbServerName = (char *)element->GetText();
    CString strDbServerName = pszDbServerName;

    delete myDocument;

3、修改某一元素文本
TiXmlDocument *myDocument = new TiXmlDocument("config.xml");
    myDocument->LoadFile();
   
    TiXmlNode  * node = myDocument->FirstChild("configs")->FirstChild("HelpFile")->FirstChild("name");
    char * pszNode = (char *)node->Value();
    if(!node)
    {
        ASSERT(FALSE);
        return;
    }
   
    TiXmlElement * element = node->ToElement();
    char * pszElement = (char *)element->GetText();


    if(!element)
    {
        ASSERT(FALSE);
        return;
    }
    //先清除文本
    node->Clear();
    TiXmlText * HelpFileContent = new TiXmlText("hdlcnet.chm");
    element->LinkEndChild(HelpFileContent);

    //element->ReplaceChild(node, HelpFileContent);

    myDocument->SaveFile("config.xml");
 
    //
    delete myDocument;

你可能感兴趣的:(C++)