參考:http://blog.csdn.net/educast/article/details/12908455
1.配置TinyXML2
去這里把項目弄下來,然后解壓,我們之需要里面的tinyxml2.h和tinyxml2.cpp,將他們拷到工程目錄里面。
2.HelloWorld
在項目中創建test.xml,內容如下:
- <?xml version="1.0"?>
- <Hello>World</Hello>
創建main.cpp
- #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;
- }
編譯運行:

3.稍微復雜一些的例子
下面這個例子的場景更可能在工程中遇到,就是在XML中存儲一些數據,然后由程序來調用。
- <?xml version="1.0"?>
- <scene name="Depth">
- <node type="camera">
- <eye>0 10 10</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>
- #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;
- }
運行結果

解釋一下幾個函數:
FirstChildElement(const char* value=0):獲取第一個值為value的子節點,value默認值為空,則返回第一個子節點。
RootElement():獲取根節點,相當於FirstChildElement的空參數版本;
const XMLAttribute* FirstAttribute() const:獲取第一個屬性值;
XMLHandle NextSiblingElement( const char* _value=0 ) :獲得下一個節點。
