例程很简单,因此就不再啰嗦了,直接上代码。
test.xml内容:
<?xml version="1.0"?>
<scene name="Depth">
<surface id="A001" type="Camera">
<eye>0 10 10</eye>
<front>0 0 -1</front>
<refUp>0 1 0</refUp>
<fov>90</fov>
</surface>
<surface id="A002" type="Sphere">
<center>0 10 -10</center>
<radius>10</radius>
</surface>
<surface id="A003" type="Plane">
<direction>0 10 -10</direction>
<distance>10</distance>
</surface>
</scene>
读XML的例程:
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main( int argc, char* argv[] )
{
XMLDocument doc;
if ( doc.LoadFile("test.xml") )
{
doc.PrintError();
exit( 1 );
}
// 根元素
XMLElement* scene = doc.RootElement();
cout << "name:" << scene->Attribute( "name" ) << endl << endl;
// 遍历<surface>元素
XMLElement* surface = scene->FirstChildElement( "surface" );
while (surface)
{
// 遍历属性列表
const XMLAttribute* surfaceAttr = surface->FirstAttribute();
while ( surfaceAttr )
{
cout << surfaceAttr->Name() << ":" << surfaceAttr->Value() << " ";
surfaceAttr = surfaceAttr->Next();
}
cout << endl;
// 遍历子元素
XMLElement* surfaceChild = surface->FirstChildElement();
while (surfaceChild)
{
cout << surfaceChild->Name() << " = " << surfaceChild->GetText() << endl;
surfaceChild = surfaceChild->NextSiblingElement();
}
cout << endl;
surface = surface->NextSiblingElement( "surface" );
}
return 0;
}
写XML的例程:
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main( int argc, char* argv[] )
{
XMLDocument doc;
// 创建根元素<China>
XMLElement* root = doc.NewElement( "China" );
doc.InsertEndChild( root );
// 创建子元素<City>
XMLElement* cityElement = doc.NewElement( "City" );
cityElement->SetAttribute( "name", "WuHan" ); // 设置元素属性
root->InsertEndChild( cityElement );
// 创建孙元素<population>
XMLElement* populationElement = doc.NewElement( "population" );
populationElement->SetText( "8,000,000" ); // 设置元素文本
cityElement->InsertEndChild( populationElement );
// 创建孙元素<area>
XMLElement* areaElement = doc.NewElement( "area" );
XMLText* areaText = doc.NewText( "10000" );
areaElement->InsertEndChild( areaText ); // 设置元素文本
cityElement->InsertEndChild( areaElement );
// 输出XML至文件
cout << "output xml to '1.xml'" << endl << endl;
doc.SaveFile( "1.xml" );
// 输出XML至内存
cout << "output xml to memory" << endl
<< "--------------------" << endl;
XMLPrinter printer;
doc.Print( &printer );
cout << printer.CStr();
return 0;
}
生成的1.xml内容:
<China>
<City name="WuHan">
<population>8,000,000</population>
<area>10000</area>
</City>
</China>