TinyXML读写XML文件

前端之家收集整理的这篇文章主要介绍了TinyXML读写XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近要用c++来读写配置文件,和自己的需要记录的数据,这这东西比存在数据库里面好用,但是唯一不爽的一点是可维护性太差,修改字段后太难处理了,没有PHP拿到参数方便,可以直接以字符串来索引查找参数的值,只能以相对位置,先拿到根目录,然后再根据相对位置查找。

这个东西的好处是可以直接拿来源码用,只有6个文件,放到你的工程里就好了。

文件

#include "tinystr.h"
#include "tinyxml.h"

贴下自己读配置文件代码,方便以后使用时查找。。
void QuoteReadConfig::ReadConfig(const char* FilePath)
{
	
	TiXmlDocument *myDocument = new TiXmlDocument(FilePath);
	if (myDocument->ErrorId() > 0)
		return;
	myDocument->LoadFile();

	TiXmlElement *QuoteConfig = myDocument->RootElement();
	TiXmlElement *Logdir = QuoteConfig->FirstChildElement();
	quoteConfig->logdir = Logdir->GetText();
	
	TiXmlElement *SetUpperNo = Logdir->NextSiblingElement();
	TiXmlElement *UpperChannelNo = SetUpperNo->FirstChildElement();
	TiXmlElement *UpperNo = UpperChannelNo->NextSiblingElement();
	TiXmlElement *PostID = UpperNo->NextSiblingElement();
	if (UpperChannelNo != NULL)
		quoteConfig->UpperChannelNo = UpperChannelNo->GetText();
	cout << quoteConfig->UpperChannelNo << endl;
	if (UpperNo != NULL)
		quoteConfig->UpperNo = UpperNo->GetText();
	if (PostID != NULL)
		quoteConfig->PostID = PostID->GetText();
	
	TiXmlElement *QuoteBusAddress = SetUpperNo->NextSiblingElement();
	TiXmlElement *BusName = QuoteBusAddress->FirstChildElement();
	TiXmlElement *IP = BusName->NextSiblingElement();
	TiXmlElement *Port = IP->NextSiblingElement();
	TiXmlElement *userNo = Port->NextSiblingElement();
	TiXmlElement *password = userNo->NextSiblingElement();
	if (BusName != NULL)
		quoteConfig->QBusName = BusName->GetText();
	cout << BusName->GetText() << endl;
	if (IP != NULL)
		quoteConfig->QIP = IP->GetText();
	if(Port != NULL)
		quoteConfig->QPort = Port->GetText();
	if (userNo != NULL)
		quoteConfig->QuserNo = userNo->GetText();
	if (password != NULL)
		quoteConfig->Qpassword = password->GetText();

	TiXmlElement *ManageBusAddress = QuoteBusAddress->NextSiblingElement();
	BusName = ManageBusAddress->FirstChildElement();
	IP = BusName->NextSiblingElement();
	Port = IP->NextSiblingElement();
	userNo = Port->NextSiblingElement();
	password = userNo->NextSiblingElement();
	if (BusName != NULL)
		quoteConfig->MBusName = BusName->GetText();
	if (IP != NULL)
		quoteConfig->MIP = IP->GetText();
	if (Port != NULL)
		quoteConfig->MPort = Port->GetText();
	if (userNo != NULL)
		quoteConfig->MuserNo = userNo->GetText();
	if (password != NULL)
		quoteConfig->Mpassword = password->GetText();

	if (myDocument != NULL)
	{
		delete myDocument;
		myDocument = NULL;
	}
}

猜你在找的XML相关文章