c++xml解析之tinyxml2
读取和设置xml配置文件是最常用的操作,试用了几个C++的XML解析器,个人感觉TinyXML是使用起来最舒服的,因为它的API接口和Java的十分类似,面向对象性很好。
TinyXML是一个开源的解析XML的解析库,能够用于C++,能够在Windows或Linux中编译。这个解析库的模型通过解析XML文件,然后在内存中生成DOM模型,从而让我们很方便的遍历这棵XML树。
DOM模型即文档对象模型,是将整个文档分成多个元素(如书、章、节、段等),并利用树型结构表示这些元素之间的顺序关系以及嵌套包含关系。
不过官方的文档并不是很完善,例子更是不知所云...然后就有了下面的内容。
这里用的是TinyXML2,相比于TinyXML1,它更小,更轻量,内存的使用也更加有效。
1.配置TinyXML2
去这里把项目弄下来,然后解压,我们之需要里面的tinyxml2.h和tinyxml2.cpp,将他们拷到工程目录里面。
2.HelloWorld
在项目中创建test.xml,内容如下:
- <?xmlversion="1.0"?>
- <Hello>World</Hello>
创建main.cpp
3.稍微复杂一些的例子
下面这个例子的场景更可能在工程中遇到,就是在XML中存储一些数据,然后由程序来调用。
- <?xmlversion="1.0"?>
- <scenename="Depth">
- <nodetype="camera">
- <eye>01010</eye>
- <front>00-1</front>
- <refUp>010</refUp>
- <fov>90</fov>
- </node>
- <nodetype="Sphere">
- <center>010-10</center>
- <radius>10</radius>
- </node>
- <nodetype="Plane">
- <direction>010-10</direction>
- <distance>10</distance>
- </node>
- </scene>
- #include<iostream>
- #include"tinyxml2.h"
- usingnamespacestd;
- usingnamespacetinyxml2;
- voidexample2()
- {
- XMLDocumentdoc;
- doc.LoadFile("test.xml");
- XMLElement*scene=doc.RootElement();
- XMLElement*surface=scene->FirstChildElement("node");
- while(surface)
- {
- XMLElement*surfaceChild=surface->FirstChildElement();
- constchar*content;
- constXMLAttribute*attributeOfSurface=surface->FirstAttribute();
- cout<<attributeOfSurface->Name()<<":"<<attributeOfSurface->Value()<<endl;
- while(surfaceChild)
- {
- content=surfaceChild->GetText();
- surfaceChild=surfaceChild->NextSiblingElement();
- cout<<content<<endl;
- }
- surface=surface->NextSiblingElement();
- }
- }
- intmain()
- {
- example1();
- return0;
- }
运行结果
解释一下几个函数:
FirstChildElement(const char* value=0):获取第一个值为value的子节点,value默认值为空,则返回第一个子节点。
RootElement():获取根节点,相当于FirstChildElement的空参数版本;
const XMLAttribute* FirstAttribute() const:获取第一个属性值;
XMLHandle NextSiblingElement( const char* _value=0 ) :获得下一个节点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。