使用tinyXml读写文件

来源:互联网 发布:雪梨cherie的淘宝店铺 编辑:程序博客网 时间:2024/04/28 23:35

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"


原创粉丝点击