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、运行结果