1、讀寫文件名稱爲config.xml ,文件內容如下
<mysql>
<userconfig name="root" pwd="mysql" />
<dbconfig addr="192.168.10.142" />
</mysql>
2、寫文件代碼
TiXmlDocument* m_xmlDoc = new TiXmlDocument();
TiXmlElement xElement("mysql");
//userconfig
std::string sbuf;
TiXmlElement userconfig("userconfig");
sbuf="root";
userconfig.SetAttribute("name", sbuf.c_str());
sbuf="mysql";
userconfig.SetAttribute("pwd", sbuf.c_str());
xElement.InsertEndChild(userconfig);
//dbconfig
TiXmlElement dbconfig("dbconfig");
sbuf="192.168.10.142";
dbconfig.SetAttribute("addr",sbuf.c_str());
xElement.InsertEndChild(dbconfig);
m_xmlDoc->InsertEndChild(xElement);
//save file
sbuf="config.xml";
m_xmlDoc->SaveFile(sbuf.c_str());
delete m_xmlDoc;
3、讀文件代碼
std::string str;
TiXmlDocument*myconfig = new TiXmlDocument();
if (myconfig->LoadFile("config.xml"))
{
TiXmlElement*xmysql=myconfig->FirstChildElement("mysql");
if (xmysql)
{
TiXmlElement*xuserconfig=xmysql->FirstChildElement("userconfig");
if (xuserconfig)
{
std::string s0=xuserconfig->Attribute("name");
str+=s0;
std::string s1=xuserconfig->Attribute("pwd");
str+=s1;
}
TiXmlElement*xdbconfig=xuserconfig->NextSiblingElement("dbconfig");
if (xdbconfig)
{
std::string s3=xdbconfig->Attribute("addr");
str+=s3;
}
TiXmlElement*xsomeconfig=xuserconfig->NextSiblingElement("someconfig");
if (xsomeconfig)
{
std::string s3=xsomeconfig->Attribute("name");
str+=s3;
}
}
}
delete myconfig;
4、環境vs2010 頭文件 tinystr.h tinyxml.h 庫文件 tinyxml.lib
在調用代碼的cXX文件頭添加 #include "tinyxml.h"