tinyxml2读写XML文件的例程

例程很简单,因此就不再啰嗦了,直接上代码。


test.xml内容:



	
		0 10 10
		0 0 -1
		0 1 0
		90
	
	
		
0 10 -10
10
0 10 -10 10

读XML的例程:

#include 
#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;

	// 遍历元素
	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 
#include "tinyxml2.h"

using namespace std;
using namespace tinyxml2;

int main( int argc, char* argv[] )
{
	XMLDocument doc;

	// 创建根元素
	XMLElement* root = doc.NewElement( "China" );
	doc.InsertEndChild( root );

	// 创建子元素
	XMLElement* cityElement = doc.NewElement( "City" );
	cityElement->SetAttribute( "name", "WuHan" ); // 设置元素属性
	root->InsertEndChild( cityElement );

	// 创建孙元素
	XMLElement* populationElement = doc.NewElement( "population" );
	populationElement->SetText( "8,000,000" ); // 设置元素文本
	cityElement->InsertEndChild( populationElement );

	// 创建孙元素
	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内容:


    
        8,000,000
        10000
    


你可能感兴趣的:(tinyxml2读写XML文件的例程)