现在的位置: 首页 > 综合 > 正文

c++ 使用TinyXml读写Xml

2019年05月30日 ⁄ 综合 ⁄ 共 2205字 ⁄ 字号 评论关闭

最近,因为要读取xml找了半天,才弄到TinyXml来读写xml。这个他们评价都还不错,所以就研究了下。不过我,也就是简单学习下。了解不深。

TinyXml的下载之后,文件比较多。其实很多都没有用,主要的就6个文件,2个 h头文件,4个cpp文件。

tinystr.cpp、tinystr.h、tinyxml.cpp、tinyxml.h、tinyxmlerror.cpp、tinyxmlparser.cpp

我整理了下,放到资源里去,欢迎大家去下载:  http://download.csdn.net/detail/open520yin/4827542

注意:这6个文件,不能复制到你们的项目里去,这样好像不能用。include好像有点问题。建议你们,自己新建文件,然后吧代码考进去。我刚开始就复制过去,怎么都不行。。。急切不要像我一样偷懒,新手不能偷懒的。呵呵。

而且,复制进去之后,在这4个cpp文件的最上面加上

 #include "stdafx.h"

我不知道是不是4个都要加,反正我是都加了,运行也是对的。

下面是我一个实例:大家可以看看。注释很清楚的。

// ConsoleApplication11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include "tinyxml.h"   
#include "tinystr.h"

using namespace std;
//定义一个类存储数据
class Person
{
public:
	string	m_sName;
	string	m_sNickName;
	int		m_nAge;
};
//保存一个xml数据
void SaveXml(Person* person, string file)
{	
	TiXmlDocument xmlDoc;
	//生成一个根节点
	TiXmlNode* rootElement = xmlDoc.InsertEndChild(TiXmlElement("Person"));
	//插入一个元素
	rootElement
		->InsertEndChild(TiXmlElement("Name"))
		->InsertEndChild(TiXmlText(person->m_sName.c_str()));
	//插入一个元素
	rootElement
		->InsertEndChild(TiXmlElement("NickName"))
		->InsertEndChild(TiXmlText(person->m_sNickName.c_str()));
	//插入一个元素
	char buffer[256];
	_itoa(person->m_nAge, buffer,10);
	rootElement
		->InsertEndChild(TiXmlElement("Age"))
		->InsertEndChild(TiXmlText(buffer));
	//保存
	xmlDoc.SaveFile(file.c_str());
}
//读取一个xml数据
void LoadXml(string file, Person* person)
{	
	//加载数据
	TiXmlDocument xmlDoc(file.c_str());
	xmlDoc.LoadFile();
	//返回错误
	if(xmlDoc.ErrorId() > 0)
		return;
	//获得根元素,即Persons。
	TiXmlElement* pRootElement = xmlDoc.RootElement();

	//如果没有空
	if(!pRootElement)
		return;

	TiXmlElement* pNode = NULL;
	//获取name节点数据
	pNode = pRootElement->FirstChildElement("Name");
	if(pNode)
	{
		person->m_sName = pNode->GetText();		
	}
	//获取NickName节点数据
	pNode = pRootElement->FirstChildElement("NickName");
	if(pNode)
	{
		person->m_sNickName = pNode->GetText();		
	}
	//获取Age节点数据
	pNode = pRootElement->FirstChildElement("Age");
	if(pNode)
	{
		person->m_nAge = atoi(pNode->GetText());		
	}
}
//主函数
int _tmain(int argc, _TCHAR* argv[])
{
	string file = "Person.xml";

	Person Larry;
	Larry.m_sName		= "Larry";
	Larry.m_sNickName	= "蹂躪";
	Larry.m_nAge		= 30;
	
	SaveXml(&Larry, file);


	Person NewLarry;
	//获取一个数据,并用NewLarry保存
	LoadXml(file, &NewLarry);

	printf("Name: %s\r\n", NewLarry.m_sName.c_str());
	printf("NickName: %s\r\n", NewLarry.m_sNickName.c_str());
	printf("Age: %d\r\n", NewLarry.m_nAge);

	return 0;
}

抱歉!评论已关闭.