1. 程式人生 > >tinyxml2讀寫XML檔案的例程

tinyxml2讀寫XML檔案的例程

例程很簡單,因此就不再囉嗦了,直接上程式碼。

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>