TinyXML2 读取

TinyXML是一个开源的解析XML的解析库,能够用于C++,能够在Windows或Linux中编译。这个解析库的模型通过解析XML文件,然后在内存中生成DOM模型,从而让我们很方便的遍历这棵XML树。

DOM模型即文档对象模型,是将整个文档分成多个元素(如书、章、节、段等),并利用树型结构表示这些元素之间的顺序关系以及嵌套包含关系。

官方文档及下载:

http://www.grinninglizard.com/tinyxml2docs/index.html

https://github.com/leethomason/tinyxml2


1、配置TinyXML2

下载后,把tinyxml2.h和tinyxml2.cpp拷贝到工程里


2、创建XLM文件

<?xml version="1.0"?>
<Persons>
	<Person ID="1" sex="Male">
		<name>Jack</name>
		<age>20</age>
	</Person>
	<Person ID="2" sex="Female">
		<name>Rose</name>
		<age>18</age>
	</Person>
</Persons>

3、创建测试工程

#include "tinyxml2.h"
using namespace tinyxml2;

void readXML();
int main()
{
	readXML();
	system("pause");
	return 0;
}

void readXML()
{
	XMLDocument doc;
	doc.LoadFile("xml.xml");

	XMLElement* root = doc.RootElement();
	printf("%s:\n",root->Name());

	XMLElement* child = root->FirstChildElement();
	//it's ok,too.
	//XMLElement* child = root->FirstChildElement("Person");
	
	printf("%s:\n",child->Name());

	//attribute of <person>
	const XMLAttribute* attribute = child->FirstAttribute();
	printf(" %s:%s\n",attribute->Name(),attribute->Value());
	
	attribute = attribute->Next();
	printf(" %s:%s\n",attribute->Name(),attribute->Value());

	//childElement of <person>
	XMLElement* grandChild = child->FirstChildElement();
	printf("%s:%s\n",grandChild->Name(),grandChild->GetText());
	
	grandChild = grandChild->NextSiblingElement();
	printf("%s:%s\n\n",grandChild->Name(),grandChild->GetText());

	/
	//2nd element
	child = child->NextSiblingElement();

	printf("%s:\n",child->Name());

	const XMLAttribute* attribute2 = child->FirstAttribute();
	printf(" %s:%s\n",attribute2->Name(),attribute2->Value());

	attribute2 = attribute2->Next();
	printf(" %s:%s\n",attribute2->Name(),attribute2->Value());

	XMLElement* grandChild2 = child->FirstChildElement();
	printf("%s:%s\n",grandChild2->Name(),grandChild2->GetText());

	grandChild2 = grandChild2->NextSiblingElement();
	printf("%s:%s\n\n",grandChild2->Name(),grandChild2->GetText());
}

4、运行结果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值