Reference: http://blog.csdn.net/educast/article/details/12908455
1. Configure TinyXML2
Go here to get the project down, then unzip, we need the inside of the Tinyxml2.h and Tinyxml2.cpp, will they cuff to the project directory.
2.HelloWorld
Create the Test.xml in the project as follows:
[HTML]View Plaincopy
- <? XML version="1.0"?>
- <hello>world</Hello>
Create Main.cpp
[CPP]View Plaincopy
- #include <iostream>
- #include "Tinyxml2.h"
- Using namespace std;
- Using namespace TINYXML2;
- void Example1 ()
- {
- XMLDocument Doc;
- Doc. LoadFile ("Test.xml");
- Const char* content= Doc. Firstchildelement ( "Hello")->gettext ();
- printf ( "hello,%s", content);
- }
- int main ()
- {
- Example1 ();
- return 0;
- }
Compile run:
3. A slightly more complex example
The scenario in the following example is more likely to be encountered in the project, which is to store some data in XML, which is then called by the program.
[HTML]View Plaincopy
- <? XML version="1.0"?>
- <scene name="Depth">
- <node type="Camera">
- <eye>0 ten</eye>
- <front>0 0-1</front>
- <refup>0 1 0</refup>
- <fov>90</fov>
- </node>
- <node type="Sphere">
- <center>0 10-10</Center>
- <radius>10</radius>
- </node>
- <node type="Plane">
- <direction>0 10-10</Direction>
- <distance>10</distance>
- </node>
- </Scene>
[CPP]View Plaincopy
- #include <iostream>
- #include "Tinyxml2.h"
- Using namespace std;
- Using namespace TINYXML2;
- void Example2 ()
- {
- XMLDocument Doc;
- Doc. LoadFile ("Test.xml");
- XMLElement *scene=doc. RootElement ();
- XMLElement *surface=scene->firstchildelement ("node");
- While (surface)
- {
- XMLElement *surfacechild=surface->firstchildelement ();
- const char* content;
- const XmlAttribute *attributeofsurface = Surface->firstattribute ();
- cout<< attributeofsurface->name () << ":" << attributeofsurface->value () << Endl;
- While (Surfacechild)
- {
- Content=surfacechild->gettext ();
- Surfacechild=surfacechild->nextsiblingelement ();
- cout<<content<<endl;
- }
- Surface=surface->nextsiblingelement ();
- }
- }
- int main ()
- {
- Example1 ();
- return 0;
- }
Run results
Explain some of the functions:
Firstchildelement (const char* value=0): Gets the first child node that is value, and the value default value is NULL, the first child node is returned.
RootElement (): Gets the root node, which is equivalent to the null parameter version of firstchildelement;
Const xmlattribute* FirstAttribute () const: Gets the value of the first property;
Xmlhandle nextsiblingelement (const char* _value=0): Gets the next node.
Library [C++]TINYXML2 Use Summary