讀取和設置xml配置文件是最經常使用的操作,試用了幾個C++的XML解析器,個人感覺TinyXML是使用起來最舒服的,由於它的API接口和Java的十分類似。面向對象性非常好。
TinyXML是一個開源的解析XML的解析庫,可以用於C++,可以在Windows或Linux中編譯。這個解析庫的模型通過解析XML文件。然后在內存中生成DOM模型。從而讓我們非常方便的遍歷這棵XML樹。
DOM模型即文檔對象模型,是將整個文檔分成多個元素(如書、章、節、段等),並利用樹型結構表示這些元素之間的順序關系以及嵌套包括關系。
只是官方的文檔並非非常完好。樣例更是不知所雲...然后就有了以下的內容。
這里用的是TinyXML2,相比於TinyXML1,它更小,更輕量,內存的使用也更加有效。
1.配置TinyXML2
去這里把項目弄下來。然后解壓,我們之須要里面的tinyxml2.h和tinyxml2.cpp,將他們拷到project文件夾里面。
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.略微復雜一些的樣例
以下這個樣例的場景更可能在project中遇到,就是在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 ) :獲得下一個節點。