在C++中使用TinyXML2解析xml
讀取和設定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,內容如下:
[html]
- <?xml version="1.0"?>
- <Hello>World</Hello>
建立main.cpp
[cpp] view plain copy
- #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中儲存一些資料,然後由程式來呼叫。
[html] view plain copy
- <?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>
[cpp] view plain copy
- #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 ) :獲得下一個節點。
再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://www.cnblogs.com/captainbed