Exemplo n.º 1
0
void readSchoolXml() {
    //using namespace std;
    const char * xmlFile = "conf/school.xml";
    TiXmlDocument doc;                              
    if (doc.LoadFile(xmlFile)) {
        doc.Print();
    } else {
        //cout << "can not parse xml conf/school.xml" << endl;
        return;
    }
    TiXmlElement* rootElement = doc.RootElement();  //School元素  
    TiXmlElement* classElement = rootElement->FirstChildElement();  // Class元素
    TiXmlElement* studentElement = classElement->FirstChildElement();  //Students  
    for (; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) {
        TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute();  //获得student的name属性  
        for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) {
            //cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;       
        }                                 

        TiXmlElement* studentContactElement = studentElement->FirstChildElement();//获得student的第一个联系方式 
        for (; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) {
            //string contactType = studentContactElement->Value();
            //string contactValue = studentContactElement->GetText();
            //cout << contactType  << " : " << contactValue << std::endl;           
        }   
     
    } 
}
Exemplo n.º 2
0
void printSchoolXml() {
	using namespace std;
	TiXmlDocument doc;  
	const char * xmlFile = "conf/school.xml";	
	if (doc.LoadFile(xmlFile)) {  	
		doc.Print();  
	} else {
		cout << "can not parse xml conf/school.xml" << endl;
	}
}
Exemplo n.º 3
0
bool TreeImportExport::saveXmlToFile(const TiXmlDocument& doc, const WCHAR * xmlFilePath)
{
	FILE * pFile = 0;
	if (_wfopen_s(&pFile, xmlFilePath, L"wb") == 0)
	{
		doc.Print(pFile);
		fclose(pFile);
		return true;
	}
	else
	{
		return false;
	}
}
Exemplo n.º 4
0
/**
 * 实现xml文件装载
 * @param[in] xml_file_path xml文件路径
 * @return NULL 装载失败
 * @return !NULL xml dom根节点
 */
libxml_node_t* libxml_file_load(const char* xml_file_path)
{
	TiXmlDocument* doc = new TiXmlDocument(xml_file_path);
	bool loadOkay = doc->LoadFile();

	if (!loadOkay)
	{
		printf("Could not load file '%s'. Error='%s'\n", xml_file_path,
				doc->ErrorDesc());
		return NULL;
	}

	doc->Print(stdout);
	return (libxml_node_t*) doc->RootElement();
}
Exemplo n.º 5
0
void EnemyManager::ReadXmlEnemyData(const char* filename)
{
	TiXmlDocument doc;
	if (doc.LoadFile(filename)) {
		doc.Print();
	} else {
		MyLog::put(__LINE__, __FILE__, "can not parse xml file.\n");
		return;
	}

	TiXmlElement* rootElement = doc.RootElement();
	TiXmlElement* keyElement = rootElement->FirstChildElement();

	while (keyElement) {
		EnemyData ed;
		TiXmlElement* ele = keyElement->FirstChildElement();
		TiXmlAttribute* coord = ele->FirstAttribute();
		ed.x = atoi(coord->Value());
		coord = coord->Next();
		ed.y = atoi(coord->Value());
		coord = coord->Next();
		ed.z = atoi(coord->Value());

		ele = ele->NextSiblingElement();
		TiXmlElement* cmdEle = ele->FirstChildElement();
		while (cmdEle) {
			TiXmlAttribute* cmdName = cmdEle->FirstAttribute();
			if (strcmp(cmdName->Value(), "MovingForward") == 0) {
				ed.vCmd.push_back(Job::eMovingForward);
			} else if (strcmp(cmdName->Value(), "TurningLeft") == 0) {
				ed.vCmd.push_back(Job::eTurningLeft);
			} else if (strcmp(cmdName->Value(), "TurningRight") == 0) {
				ed.vCmd.push_back(Job::eTurningRight);
			}
			cmdEle = cmdEle->NextSiblingElement();
		}

		vData.push_back(ed);
		keyElement = keyElement->NextSiblingElement();
	}
}
Exemplo n.º 6
0
void readXml()
{
    TiXmlDocument* myDocument = new TiXmlDocument();
    myDocument->LoadFile("student.xml");
    myDocument->Print();
    TiXmlElement* rootElement = myDocument->RootElement();  //Class    
    TiXmlElement* studentsElement = rootElement->FirstChildElement();  //Students
    TiXmlElement* studentElement = studentsElement->FirstChildElement();  //Students
    //std::cout<<studentElement->GetText() ;    
    while ( studentElement ) 
    {
        TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute();  //获得student的name属性
        while ( attributeOfStudent ) 
        {
            std::cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;
            attributeOfStudent = attributeOfStudent->Next();
        }
        TiXmlElement* phoneElement = studentElement->FirstChildElement();//获得student的phone元素
        std::cout << "phone" << " : " << phoneElement->GetText() << std::endl;
        TiXmlElement* addressElement = phoneElement->NextSiblingElement();
        std::cout << "address" << " : " << phoneElement->GetText() << std::endl;
        studentElement = studentElement->NextSiblingElement();
    }
}
Exemplo n.º 7
0
void SceneImporter::serialise()
{
	BinaryDataStore<char> binaryDataStore;
	TiXmlDocument doc;
	TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", "");
	doc.LinkEndChild(decl);
	TiXmlElement* root = new TiXmlElement("root");
	doc.LinkEndChild(root);
	TiXmlElement* header = new TiXmlElement("Header");
	header->SetAttribute("type", "SkinnedCharacter");
	root->LinkEndChild(header);
	TiXmlElement* prefab = new TiXmlElement("Model");
	root->LinkEndChild(prefab);
	TiXmlElement* meshes = new TiXmlElement("Meshes");
	prefab->LinkEndChild(meshes);
	meshes->SetAttribute("count", _meshes.size());
	for (auto It = _meshes.begin(); It != _meshes.end(); It++)
	{
		auto_ptr<Mesh>& meshPtr = *(It);
		meshPtr->serialise(meshes, binaryDataStore);
	}
	Animator::get()->serialise(prefab, binaryDataStore);
	const char* fileName = "prefab.xml";
	ofstream os;
	binaryDataStore.compact();
	os.open(fileName, ios::binary);
	long numBinaryBytes = binaryDataStore.size();
	os.write((const char*)&numBinaryBytes, sizeof(long));
	const vector<char>& buffer = binaryDataStore.getBuffer();
	os.write(&buffer[0], numBinaryBytes);
	os.close();
	FILE* fp;
	fp = fopen(fileName, "a");
	doc.Print(fp);
	fclose(fp);
}
Exemplo n.º 8
0
int main()
{

	//
	// We start with the 'demoStart' todo list. Process it. And
	// should hopefully end up with the todo list as illustrated.
	//
	const char* demoStart =
		"<?xml version=\"1.0\"  standalone='no' >\n"
		"<!-- Our to do list data -->"
		"<ToDo>\n"
		"<!-- Do I need a secure PDA? -->\n"
		"<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
		"<Item priority=\"2\" distance='none'> Do bills   </Item>"
		"<Item priority=\"2\" distance='far &amp; back'> Look for Evil Dinosaurs! </Item>"
		"</ToDo>";
		
	{

	#ifdef TIXML_USE_STL
		//	What the todo list should look like after processing.
		// In stream (no formatting) representation.
		const char* demoEnd =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<!-- Our to do list data -->"
			"<ToDo>"
			"<!-- Do I need a secure PDA? -->"
			"<Item priority=\"2\" distance=\"close\">Go to the"
			"<bold>Toy store!"
			"</bold>"
			"</Item>"
			"<Item priority=\"1\" distance=\"far\">Talk to:"
			"<Meeting where=\"School\">"
			"<Attendee name=\"Marple\" position=\"teacher\" />"
			"<Attendee name=\"Voel\" position=\"counselor\" />"
			"</Meeting>"
			"<Meeting where=\"Lunch\" />"
			"</Item>"
			"<Item priority=\"2\" distance=\"here\">Do bills"
			"</Item>"
			"</ToDo>";
	#endif

		// The example parses from the character string (above):
		#if defined( WIN32 ) && defined( TUNE )
		_CrtMemCheckpoint( &startMemState );
		#endif	

		{
			// Write to a file and read it back, to check file I/O.

			TiXmlDocument doc( "demotest.xml" );
			doc.Parse( demoStart );

			if ( doc.Error() )
			{
				printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
				exit( 1 );
			}
			doc.SaveFile();
		}

		TiXmlDocument doc( "demotest.xml" );
		bool loadOkay = doc.LoadFile();

		if ( !loadOkay )
		{
			printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
			exit( 1 );
		}

		printf( "** Demo doc read from disk: ** \n\n" );
		printf( "** Printing via doc.Print **\n" );
		doc.Print( stdout );

		{
			printf( "** Printing via TiXmlPrinter **\n" );
			TiXmlPrinter printer;
			doc.Accept( &printer );
			fprintf( stdout, "%s", printer.CStr() );
		}
		#ifdef TIXML_USE_STL	
		{
			printf( "** Printing via operator<< **\n" );
			std::cout << doc;
		}
		#endif
		TiXmlNode* node = 0;
		TiXmlElement* todoElement = 0;
		TiXmlElement* itemElement = 0;


		// --------------------------------------------------------
		// An example of changing existing attributes, and removing
		// an element from the document.
		// --------------------------------------------------------

		// Get the "ToDo" element.
		// It is a child of the document, and can be selected by name.
		node = doc.FirstChild( "ToDo" );
		assert( node );
		todoElement = node->ToElement();
		assert( todoElement  );

		// Going to the toy store is now our second priority...
		// So set the "priority" attribute of the first item in the list.
		node = todoElement->FirstChildElement();	// This skips the "PDA" comment.
		assert( node );
		itemElement = node->ToElement();
		assert( itemElement  );
		itemElement->SetAttribute( "priority", 2 );

		// Change the distance to "doing bills" from
		// "none" to "here". It's the next sibling element.
		itemElement = itemElement->NextSiblingElement();
		assert( itemElement );
		itemElement->SetAttribute( "distance", "here" );

		// Remove the "Look for Evil Dinosaurs!" item.
		// It is 1 more sibling away. We ask the parent to remove
		// a particular child.
		itemElement = itemElement->NextSiblingElement();
		todoElement->RemoveChild( itemElement );

		itemElement = 0;

		// --------------------------------------------------------
		// What follows is an example of created elements and text
		// nodes and adding them to the document.
		// --------------------------------------------------------

		// Add some meetings.
		TiXmlElement item( "Item" );
		item.SetAttribute( "priority", "1" );
		item.SetAttribute( "distance", "far" );

		TiXmlText text( "Talk to:" );

		TiXmlElement meeting1( "Meeting" );
		meeting1.SetAttribute( "where", "School" );

		TiXmlElement meeting2( "Meeting" );
		meeting2.SetAttribute( "where", "Lunch" );

		TiXmlElement attendee1( "Attendee" );
		attendee1.SetAttribute( "name", "Marple" );
		attendee1.SetAttribute( "position", "teacher" );

		TiXmlElement attendee2( "Attendee" );
		attendee2.SetAttribute( "name", "Voel" );
		attendee2.SetAttribute( "position", "counselor" );

		// Assemble the nodes we've created:
		meeting1.InsertEndChild( attendee1 );
		meeting1.InsertEndChild( attendee2 );

		item.InsertEndChild( text );
		item.InsertEndChild( meeting1 );
		item.InsertEndChild( meeting2 );

		// And add the node to the existing list after the first child.
		node = todoElement->FirstChild( "Item" );
		assert( node );
		itemElement = node->ToElement();
		assert( itemElement );

		todoElement->InsertAfterChild( itemElement, item );

		printf( "\n** Demo doc processed: ** \n\n" );
		doc.Print( stdout );


	#ifdef TIXML_USE_STL
		printf( "** Demo doc processed to stream: ** \n\n" );
		cout << doc << endl << endl;
	#endif

		// --------------------------------------------------------
		// Different tests...do we have what we expect?
		// --------------------------------------------------------

		int count = 0;
		TiXmlElement*	element;

		//////////////////////////////////////////////////////

	#ifdef TIXML_USE_STL
		cout << "** Basic structure. **\n";
		ostringstream outputStream( ostringstream::out );
		outputStream << doc;
		XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
											outputStream.str().c_str(), true );
	#endif

		node = doc.RootElement();
		assert( node );
		XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) );
		XmlTest ( "Root element value is 'ToDo'.", "ToDo",  node->Value());

		node = node->FirstChild();
		XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) );
		node = node->NextSibling();
		XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) );
		XmlTest ( "Value is 'Item'.", "Item", node->Value() );

		node = node->FirstChild();
		XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) );
		XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() );


		//////////////////////////////////////////////////////
		printf ("\n** Iterators. **\n");

		// Walk all the top level nodes of the document.
		count = 0;
		for( node = doc.FirstChild();
			 node;
			 node = node->NextSibling() )
		{
			count++;
		}
		XmlTest( "Top level nodes, using First / Next.", 3, count );

		count = 0;
		for( node = doc.LastChild();
			 node;
			 node = node->PreviousSibling() )
		{
			count++;
		}
		XmlTest( "Top level nodes, using Last / Previous.", 3, count );

		// Walk all the top level nodes of the document,
		// using a different syntax.
		count = 0;
		for( node = doc.IterateChildren( 0 );
			 node;
			 node = doc.IterateChildren( node ) )
		{
			count++;
		}
		XmlTest( "Top level nodes, using IterateChildren.", 3, count );

		// Walk all the elements in a node.
		count = 0;
		for( element = todoElement->FirstChildElement();
			 element;
			 element = element->NextSiblingElement() )
		{
			count++;
		}
		XmlTest( "Children of the 'ToDo' element, using First / Next.",
			3, count );

		// Walk all the elements in a node by value.
		count = 0;
		for( node = todoElement->FirstChild( "Item" );
			 node;
			 node = node->NextSibling( "Item" ) )
		{
			count++;
		}
		XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count );

		count = 0;
		for( node = todoElement->LastChild( "Item" );
			 node;
			 node = node->PreviousSibling( "Item" ) )
		{
			count++;
		}
		XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count );

	#ifdef TIXML_USE_STL
		{
			cout << "\n** Parsing. **\n";
			istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '&gt;' />" );
			TiXmlElement element0( "default" );
			parse0 >> element0;

			XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() );
			XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" ));
			XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) );
			XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) );
		}
	#endif

		{
			const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
								"<passages count=\"006\" formatversion=\"20020620\">\n"
								"    <wrong error>\n"
								"</passages>";

			TiXmlDocument docTest;
			docTest.Parse( error );
			XmlTest( "Error row", docTest.ErrorRow(), 3 );
			XmlTest( "Error column", docTest.ErrorCol(), 17 );
			//printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );

		}

	#ifdef TIXML_USE_STL
		{
			//////////////////////////////////////////////////////
			cout << "\n** Streaming. **\n";

			// Round trip check: stream in, then stream back out to verify. The stream
			// out has already been checked, above. We use the output

			istringstream inputStringStream( outputStream.str() );
			TiXmlDocument document0;

			inputStringStream >> document0;

			ostringstream outputStream0( ostringstream::out );
			outputStream0 << document0;

			XmlTest( "Stream round trip correct.",	string( demoEnd ).c_str(), 
													outputStream0.str().c_str(), true );

			std::string str;
			str << document0;

			XmlTest( "String printing correct.", string( demoEnd ).c_str(), 
												 str.c_str(), true );
		}
	#endif
	}

	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: int as double", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XmlTest( "Query attribute: double as double", (int)dVal, 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE );
	}

	{
		const char* str = "<doc/>";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlElement* ele = doc.FirstChildElement();

		int iVal;
		double dVal;

		ele->SetAttribute( "str", "strValue" );
		ele->SetAttribute( "int", 1 );
		ele->SetDoubleAttribute( "double", -1.0 );

		const char* cStr = ele->Attribute( "str" );
		ele->QueryIntAttribute( "int", &iVal );
		ele->QueryDoubleAttribute( "double", &dVal );

		XmlTest( "Attribute round trip. c-string.", "strValue", cStr );
		XmlTest( "Attribute round trip. int.", 1, iVal );
		XmlTest( "Attribute round trip. double.", -1, (int)dVal );
	}
	
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"</room>";

		TiXmlDocument doc;
		doc.SetTabSize( 8 );
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );

		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );

		XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 );
		XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 );
	}
	
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"  <!-- Silly example -->\n"
							"    <door wall='north'>A great door!</door>\n"
							"\t<door wall='east'/>"
							"</room>";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );
		TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild();
		TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild();
		TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 );
		TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );
		assert( commentHandle.Node() );
		assert( textHandle.Text() );
		assert( door0Handle.Element() );
		assert( door1Handle.Element() );

		TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration();
		assert( declaration );
		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );
		TiXmlText* text = textHandle.Text();
		TiXmlComment* comment = commentHandle.Node()->ToComment();
		assert( comment );
		TiXmlElement* door0 = door0Handle.Element();
		TiXmlElement* door1 = door1Handle.Element();

		XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 );
		XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 );
		XmlTest( "Location tracking: room row", room->Row(), 1 );
		XmlTest( "Location tracking: room col", room->Column(), 45 );
		XmlTest( "Location tracking: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: doors col", doors->Column(), 51 );
		XmlTest( "Location tracking: Comment row", comment->Row(), 2 );
		XmlTest( "Location tracking: Comment col", comment->Column(), 3 );
		XmlTest( "Location tracking: text row", text->Row(), 3 ); 
		XmlTest( "Location tracking: text col", text->Column(), 24 );
		XmlTest( "Location tracking: door0 row", door0->Row(), 3 );
		XmlTest( "Location tracking: door0 col", door0->Column(), 5 );
		XmlTest( "Location tracking: door1 row", door1->Row(), 4 );
		XmlTest( "Location tracking: door1 col", door1->Column(), 5 );
	}


	// --------------------------------------------------------
	// UTF-8 testing. It is important to test:
	//	1. Making sure name, value, and text read correctly
	//	2. Row, Col functionality
	//	3. Correct output
	// --------------------------------------------------------
	printf ("\n** UTF-8 **\n");
	{
		TiXmlDocument doc( "utf8test.xml" );
		doc.LoadFile();
		if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) {
			printf( "WARNING: File 'utf8test.xml' not found.\n"
					"(Are you running the test from the wrong directory?)\n"
				    "Could not test UTF-8 functionality.\n" );
		}
		else
		{
			TiXmlHandle docH( &doc );
			// Get the attribute "value" from the "Russian" element and check it.
			TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element();
			const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 
													0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

			XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true );
			XmlTest( "UTF-8: Russian value row.", 4, element->Row() );
			XmlTest( "UTF-8: Russian value column.", 5, element->Column() );

			const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
															0xd1U, 0x81U, 0xd1U, 0x81U,
															0xd0U, 0xbaU, 0xd0U, 0xb8U,
															0xd0U, 0xb9U, 0 };
			const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

			TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text();
			XmlTest( "UTF-8: Browsing russian element name.",
					 russianText,
					 text->Value(),
					 true );
			XmlTest( "UTF-8: Russian element name row.", 7, text->Row() );
			XmlTest( "UTF-8: Russian element name column.", 47, text->Column() );

			TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration();
			XmlTest( "UTF-8: Declaration column.", 1, dec->Column() );
			XmlTest( "UTF-8: Document column.", 1, doc.Column() );

			// Now try for a round trip.
			doc.SaveFile( "utf8testout.xml" );

			// Check the round trip.
			char savedBuf[256];
			char verifyBuf[256];
			int okay = 1;
			FILE* saved  = fopen( "data/utf8testout.xml", "r" );
			FILE* verify = fopen( "data/utf8testverify.xml", "r" );

			//bool firstLineBOM=true;
			if ( saved && verify )
			{
				while ( fgets( verifyBuf, 256, verify ) )
				{
					fgets( savedBuf, 256, saved );
					NullLineEndings( verifyBuf );
					NullLineEndings( savedBuf );

					if ( /*!firstLineBOM && */ strcmp( verifyBuf, savedBuf ) )
					{
						printf( "verify:%s<\n", verifyBuf );
						printf( "saved :%s<\n", savedBuf );
						okay = 0;
						break;
					}
					//firstLineBOM = false;
				}
			}
			if ( saved )
				fclose( saved );
			if ( verify )
				fclose( verify );
			XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay );

			// On most Western machines, this is an element that contains
			// the word "resume" with the correct accents, in a latin encoding.
			// It will be something else completely on non-wester machines,
			// which is why TinyXml is switching to UTF-8.
			const char latin[] = "<element>r\x82sum\x82</element>";

			TiXmlDocument latinDoc;
			latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY );

			text = latinDoc.FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() );
		}
	}		

	//////////////////////
	// Copy and assignment
	//////////////////////
	printf ("\n** Copy and Assignment **\n");
	{
		TiXmlElement element( "foo" );
		element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN );

		TiXmlElement elementCopy( element );
		TiXmlElement elementAssign( "foo" );
		elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN );
		elementAssign = element;

		XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() );
		XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() );
		XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) );

		TiXmlComment comment;
		comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlComment commentCopy( comment );
		TiXmlComment commentAssign;
		commentAssign = commentCopy;
		XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() );
		XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() );

		TiXmlUnknown unknown;
		unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlUnknown unknownCopy( unknown );
		TiXmlUnknown unknownAssign;
		unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN );
		unknownAssign = unknownCopy;
		XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() );
		XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() );
		
		TiXmlText text( "TextNode" );
		TiXmlText textCopy( text );
		TiXmlText textAssign( "incorrect" );
		textAssign = text;
		XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() );
		XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() );

		TiXmlDeclaration dec;
		dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlDeclaration decCopy( dec );
		TiXmlDeclaration decAssign;
		decAssign = dec;

		XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() );
		XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() );

		TiXmlDocument doc;
		elementCopy.InsertEndChild( textCopy );
		doc.InsertEndChild( decAssign );
		doc.InsertEndChild( elementCopy );
		doc.InsertEndChild( unknownAssign );

		TiXmlDocument docCopy( doc );
		TiXmlDocument docAssign;
		docAssign = docCopy;

		#ifdef TIXML_USE_STL
		std::string original, copy, assign;
		original << doc;
		copy << docCopy;
		assign << docAssign;
		XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true );
		XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true );

		#endif
	}	

	//////////////////////////////////////////////////////
#ifdef TIXML_USE_STL
	printf ("\n** Parsing, no Condense Whitespace **\n");
	TiXmlBase::SetCondenseWhiteSpace( false );
	{
		istringstream parse1( "<start>This  is    \ntext</start>" );
		TiXmlElement text1( "text" );
		parse1 >> text1;

		XmlTest ( "Condense white space OFF.", "This  is    \ntext",
					text1.FirstChild()->Value(),
					true );
	}
	TiXmlBase::SetCondenseWhiteSpace( true );
#endif

	//////////////////////////////////////////////////////
	// GetText();
	{
		const char* str = "<foo>This is text</foo>";
		TiXmlDocument doc;
		doc.Parse( str );
		const TiXmlElement* element = doc.RootElement();

		XmlTest( "GetText() normal use.", "This is text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Clear();
		doc.Parse( str );
		element = doc.RootElement();

		XmlTest( "GetText() contained element.", element->GetText() == 0, true );

		str = "<foo>This is <b>text</b></foo>";
		doc.Clear();
		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Parse( str );
		TiXmlBase::SetCondenseWhiteSpace( true );
		element = doc.RootElement();

		XmlTest( "GetText() partial.", "This is ", element->GetText() );
	}


	//////////////////////////////////////////////////////
	// CDATA
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL
		//cout << doc << '\n';

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;
		//cout << doc << '\n';

		XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
	}
	{
		// [ 1482728 ] Wrong wide char parsing
		char buf[256];
		buf[255] = 0;
		for( int i=0; i<255; ++i ) {
			buf[i] = (char)((i>=32) ? i : 32);
		}
		TIXML_STRING str( "<xmlElement><![CDATA[" );
		str += buf;
		str += "]]></xmlElement>";

		TiXmlDocument doc;
		doc.Parse( str.c_str() );

		TiXmlPrinter printer;
		printer.SetStreamPrinting();
		doc.Accept( &printer );

		XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true );

		#ifdef TIXML_USE_STL
		doc.Clear();
		istringstream iss( printer.Str() );
		iss >> doc;
		std::string out;
		out << doc;
		XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true );
		#endif
	}
	{
		// [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags
		// CDATA streaming had a couple of bugs, that this tests for.
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;

		XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
	}
	//////////////////////////////////////////////////////
	// Visit()



	//////////////////////////////////////////////////////
	printf( "\n** Fuzzing... **\n" );

	const int FUZZ_ITERATION = 300;

	// The only goal is not to crash on bad input.
	int len = (int) strlen( demoStart );
	for( int i=0; i<FUZZ_ITERATION; ++i ) 
	{
		char* demoCopy = new char[ len+1 ];
		strcpy( demoCopy, demoStart );

		demoCopy[ i%len ] = (char)((i+1)*3);
		demoCopy[ (i*7)%len ] = '>';
		demoCopy[ (i*11)%len ] = '<';

		TiXmlDocument xml;
		xml.Parse( demoCopy );

		delete [] demoCopy;
	}
	printf( "** Fuzzing Complete. **\n" );
	
	//////////////////////////////////////////////////////
	printf ("\n** Bug regression tests **\n");

	// InsertBeforeChild and InsertAfterChild causes crash.
	{
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 );

		XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true );
	}

	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 );

		XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true );
	}

	// Reports of missing constructors, irregular string problems.
	{
		// Missing constructor implementation. No test -- just compiles.
		TiXmlText text( "Missing" );

		#ifdef TIXML_USE_STL
			// Missing implementation:
			TiXmlDocument doc;
			string name = "missing";
			doc.LoadFile( name );

			TiXmlText textSTL( name );
		#else
			// verifying some basic string functions:
			TiXmlString a;
			TiXmlString b( "Hello" );
			TiXmlString c( "ooga" );

			c = " World!";
			a = b;
			a += c;
			a = a;

			XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() );
		#endif
 	}

	// Long filenames crashing STL version
	{
		TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" );
		bool loadOkay = doc.LoadFile();
		loadOkay = true;	// get rid of compiler warning.
		// Won't pass on non-dev systems. Just a "no crash" check.
		//XmlTest( "Long filename. ", true, loadOkay );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
			"</passages>";

		TiXmlDocument doc( "passages.xml" );
		doc.Parse( passages );
		TiXmlElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XmlTest( "Entity transformation: read. ", expected, context, true );

		FILE* textfile = fopen( "textfile.txt", "w" );
		if ( textfile )
		{
			psg->Print( textfile, 0 );
			fclose( textfile );
		}
		textfile = fopen( "textfile.txt", "r" );
		assert( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XmlTest( "Entity transformation: write. ",
					 "<psg context=\'Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.' />",
					 buf,
					 true );
		}
		fclose( textfile );
	}

    {
		FILE* textfile = fopen( "test5.xml", "w" );
		if ( textfile )
		{
            fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile);
            fclose(textfile);

			TiXmlDocument doc;
            doc.LoadFile( "test5.xml" );
            XmlTest( "dot in element attributes and names", doc.Error(), 0);
		}
    }

	{
		FILE* textfile = fopen( "test6.xml", "w" );
		if ( textfile )
		{
            fputs("<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>", textfile );
            fclose(textfile);

            TiXmlDocument doc;
            bool result = doc.LoadFile( "test6.xml" );
            XmlTest( "Entity with one digit.", result, true );

			TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Entity with one digit.",
						text->Value(), "1.1 Start easy ignore fin thickness\n" );
		}
    }

	{
		// DOCTYPE not preserved (950171)
		// 
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "test7.xml" );
		doc.Clear();
		doc.LoadFile( "test7.xml" );
		
		TiXmlHandle docH( &doc );
		TiXmlUnknown* unknown = docH.Child( 1 ).Unknown();
		XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() );
		#ifdef TIXML_USE_STL
		TiXmlNode* node = docH.Child( 2 ).Node();
		std::string str;
		str << (*node);
		XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() );
		#endif
	}

	{
		// [ 791411 ] Formatting bug
		// Comments do not stream out correctly.
		const char* doctype = 
			"<!-- Somewhat<evil> -->";
		TiXmlDocument doc;
		doc.Parse( doctype );

		TiXmlHandle docH( &doc );
		TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment();

		XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
		#ifdef TIXML_USE_STL
		std::string str;
		str << (*comment);
		XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() );
		#endif
	}

	{
		// [ 870502 ] White space issues
		TiXmlDocument doc;
		TiXmlText* text;
		TiXmlHandle docH( &doc );
	
		const char* doctype0 = "<element> This has leading and trailing space </element>";
		const char* doctype1 = "<element>This has  internal space</element>";
		const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", "This has  internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading, trailing, and  internal space ", text->Value() );

		TiXmlBase::SetCondenseWhiteSpace( true );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() );
	}

	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		
		XmlTest( "Parsing repeated attributes.", true, doc.Error() );	// is an  error to tinyxml (didn't use to be, but caused issues)
		//XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) );
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		XmlTest( "Embedded null throws error.", true, doc.Error() );

		#ifdef TIXML_USE_STL
		istringstream strm( doctype );
		doc.Clear();
		doc.ClearError();
		strm >> doc;
		XmlTest( "Embedded null throws error.", true, doc.Error() );
		#endif
	}

    {
      /**     // Legacy mode test. (This test may only pass on a western system)
            const char* str =
                        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
                        "<?"
                        "C鰊t鋘t咪鳇闹?"
                        "</?";

            TiXmlDocument doc;
            doc.Parse( str );

            TiXmlHandle docHandle( &doc );
            TiXmlHandle aHandle = docHandle.FirstChildElement( "?" );
            TiXmlHandle tHandle = aHandle.Child( 0 );
            assert( aHandle.Element() );
            assert( tHandle.Text() );
            XmlTest( "ISO-8859-1 Parsing.", "C鰊t鋘t咪鳇闹?, tHandle.Text()->Value() ");
    }

	{
		// Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		TiXmlDocument doc;
		doc.Parse( str );
		XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() );
	}
	#ifndef TIXML_USE_STL
	{
		// String equality. [ 1006409 ] string operator==/!= no worky in all cases
		TiXmlString temp;
		XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true );

		TiXmlString    foo;
		TiXmlString    bar( "" );
		XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true );
	}

	#endif
	{
		// Bug [ 1195696 ] from marlonism
		TiXmlBase::SetCondenseWhiteSpace(false); 
		TiXmlDocument xml; 
		xml.Parse("<text><break/>This hangs</text>"); 
		XmlTest( "Test safe error return.", xml.Error(), false );
	}

	{
		// Bug [ 1243992 ] - another infinite loop
		TiXmlDocument doc;
		doc.SetCondenseWhiteSpace(false);
		doc.Parse("<p><pb></pb>test</p>");
	} 
	{
		// Low entities
		TiXmlDocument xml;
		xml.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result );
		xml.Print();
	}
	{
		// Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly
		TiXmlDocument xml;
		xml.Parse( "<foo attribute=bar\" />" );
		XmlTest( "Throw error with bad end quotes.", xml.Error(), true );
	}
	#ifdef TIXML_USE_STL
	{
		// Bug [ 1449463 ] Consider generic query
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' barStr='a string'/>" );

		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;
		float f;
		bool b;
		std::string str;

		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS );

		XmlTest( "QueryValueAttribute", (d==3.0), true );
		XmlTest( "QueryValueAttribute", (i==3), true );
		XmlTest( "QueryValueAttribute", (f==3.0f), true );
		XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true );
	}
	#endif

	#ifdef TIXML_USE_STL
	{
		// [ 1505267 ] redundant malloc in TiXmlElement::Attribute
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' />" );
		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;

		std::string bar = "bar";

		const std::string* atrrib = ele->Attribute( bar );
		ele->Attribute( bar, &d );
		ele->Attribute( bar, &i );

		XmlTest( "Attribute", atrrib->empty(), false );
		XmlTest( "Attribute", (d==3.0), true );
		XmlTest( "Attribute", (i==3), true );
	}
	#endif

	{
		// [ 1356059 ] Allow TiXMLDocument to only be at the top level
		TiXmlDocument xml, xml2;
		xml.InsertEndChild( xml2 );
		XmlTest( "Document only at top level.", xml.Error(), true );
		XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		TiXmlDocument xml;
		xml.Parse("<x>");
		XmlTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XmlTest("Missing end tag with trailing whitespace", xml.Error(), true);
	} 

	{
		// [ 1635701 ] fail to parse files with a tag separated into two lines
		// I'm not sure this is a bug. Marked 'pending' for feedback.
		TiXmlDocument xml;
		xml.Parse( "<title><p>text</p\n><title>" );
		//xml.Print();
		//XmlTest( "Tag split by newline", xml.Error(), false );
	}

	#ifdef TIXML_USE_STL
	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		istringstream parse1( "<!-- declarations for <head> & <body> -->"
						      "<!-- far &amp; away -->" );
		parse1 >> xml;

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}
	#endif

	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}

	{
		TiXmlDocument xml;
		xml.Parse( "<Parent>"
						"<child1 att=''/>"
						"<!-- With this comment, child2 will not be parsed! -->"
						"<child2 att=''/>"
					"</Parent>" );
		int count = 0;

		TiXmlNode* ele = 0;
		while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) {
			++count;
		}
		XmlTest( "Comments iterate correctly.", 3, count );
	}

	{
		// trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
		unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
		buf[60] = 239;
		buf[61] = 0;

		TiXmlDocument doc;
		doc.Parse( (const char*)buf);
	} 


	{
		// bug 1827248 Error while parsing a little bit malformed file
		// Actually not malformed - should work.
		TiXmlDocument xml;
		xml.Parse( "<attributelist> </attributelist >" );
		XmlTest( "Handle end tag whitespace", false, xml.Error() );
	}

	{
		// This one must not result in an infinite loop
		TiXmlDocument xml;
		xml.Parse( "<infinite>loop" );
		XmlTest( "Infinite loop test.", true, true );
	}

	{
		// 1709904 - can not repro the crash
		{
			TiXmlDocument xml;
			xml.Parse( "<tag>/</tag>" );
			XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" );
		}
		/* Could not repro. {
			TiXmlDocument xml;
			xml.LoadFile( "EQUI_Inventory.xml" );
			//XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" );
			TiXmlPrinter printer;
			xml.Accept( &printer );
			fprintf( stdout, "%s", printer.CStr() );
		}*/
	}

	/*  1417717 experiment
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan & Tracie</text>");
		xml.Print(stdout);
	}
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan &foo; Tracie</text>");
		xml.Print(stdout);
	}
	*/

	#if defined( WIN32 ) && defined( TUNE )
	_CrtMemCheckpoint( &endMemState );
	//_CrtMemDumpStatistics( &endMemState );

	_CrtMemState diffMemState;
	_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
	_CrtMemDumpStatistics( &diffMemState );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return gFail;
}
//case 7:open and write the current menu to a file in RBML  
	void MenuList::outputMenuList(string outFileName){
		
		cout << "Please enter the file name to be saved: " << endl;

		cin >> outFileName;

		TiXmlDocument doc;
		TiXmlDeclaration *declaration = new TiXmlDeclaration ("1.0","UTF-8","");
		doc.LinkEndChild(declaration);

		TiXmlComment *comment = new TiXmlComment ("hi, this is a recipe book");
		doc.LinkEndChild(comment);

		TiXmlElement * menuListElement = new TiXmlElement("menulist");
		doc.LinkEndChild(menuListElement);

		for (int i =0; i < menuList.size(); i++){
		
			TiXmlElement * recipeElement = new TiXmlElement("recipe");
			menuListElement->LinkEndChild(recipeElement);

			TiXmlElement * titleElement = new TiXmlElement("title");
			recipeElement->LinkEndChild(titleElement);

			TiXmlText * titleContent = new TiXmlText("Blackeyed Peas");
			titleElement->LinkEndChild(titleContent);	

		
			TiXmlElement * ingredientslistElement = new TiXmlElement("ingreidentslist");
			recipeElement->LinkEndChild(ingredientslistElement);


			for (int j =0; j < menuList[i].ingredientsList.size();j++){

				TiXmlElement * ingredientElement = new TiXmlElement("ingredient");
				ingredientslistElement->LinkEndChild(ingredientElement);
	
				TiXmlElement * quantityElement = new TiXmlElement("quantity");
				ingredientElement->LinkEndChild(quantityElement);

				TiXmlElement * unitElement = new TiXmlElement("unit");
				ingredientElement->LinkEndChild(unitElement);	

				TiXmlElement * fooditemElement = new TiXmlElement("fooditem");
				ingredientElement->LinkEndChild(fooditemElement);

				//content
				TiXmlText * quantityContent = new TiXmlText("menuList[i].ingredientsList[j].quantity.c_str");
				quantityElement->LinkEndChild(quantityContent);	

				TiXmlText * unitContent = new TiXmlText(menuList[i].ingredientsList[j].unit.c_str());
				unitElement->LinkEndChild(unitContent);	

				TiXmlText * fooditemContent = new TiXmlText(menuList[i].ingredientsList[j].fooditem.c_str());
				fooditemElement->LinkEndChild(fooditemContent);

			}


			TiXmlElement * preparationElement = new TiXmlElement("preparation");
			recipeElement->LinkEndChild(preparationElement);

			for (int j =0; j< menuList[i].equipmentList.size();j++){
				TiXmlElement * equipmentElement = new TiXmlElement("equipment");
				preparationElement->LinkEndChild(equipmentElement);

				TiXmlText* equipmentContent = new TiXmlText(menuList[i].equipmentList[j].equipment.c_str());
				equipmentElement->LinkEndChild(equipmentContent);
			}


		}

		doc.Print();
		doc.SaveFile(outFileName.c_str());

		if (!silent){
			cout << "Save to " << outFileName << " completed" << endl;
		}

		return;
	
	} 
Exemplo n.º 10
0
int main(int argc, char** argv)
{
    if( argc <  2 ) return -1;
    TiXmlDocument* doc = loadFromFile(argv[1]);

    sofa::core::init();
    int retValue = 0;

    if(doc )
    {
        DiscoverNodes v_nodes;
        DiscoverDisplayFlagsVisitor v_displayFlags;
        doc->Accept(&v_nodes);
        doc->Accept(&v_displayFlags);

        for(unsigned int i=0; i < v_nodes.leaves.size(); ++i )
        {
            createVisualStyleVisitor(v_nodes.leaves[i],v_displayFlags.map_displayFlags);
        }

        for( unsigned int i=0; i < v_nodes.nodes.size(); ++i)
        {
            removeShowAttributes(v_nodes.nodes[i]);
        }

        if( v_nodes.rootNode() )
        {
            std::map<const TiXmlElement*,sofa::core::visual::DisplayFlags*>::iterator it_root;
            it_root = v_displayFlags.map_displayFlags.find(v_nodes.rootNode());
            if( it_root != v_displayFlags.map_displayFlags.end() )
            {
                DisplayFlags* root_flags = it_root->second;
                convert_false_to_neutral(*root_flags);
                TiXmlElement* visualStyle;
                if( ! root_flags->isNeutral() )
                {
                    if( (visualStyle = v_nodes.rootNode()->FirstChildElement("VisualStyle") ) == NULL )
                    {
                        TiXmlElement* visualstyle = new TiXmlElement("VisualStyle");
                        std::ostringstream oss;
                        oss << *root_flags;
                        visualstyle->SetAttribute("displayFlags",oss.str());
                        TiXmlElement* first_child = v_nodes.rootNode()->FirstChildElement();
                        if(first_child) v_nodes.rootNode()->InsertBeforeChild(first_child,*visualstyle);
                        else v_nodes.rootNode()->LinkEndChild(visualstyle);
                    }
                    else
                    {
                        std::ostringstream oss;
                        oss << *root_flags;
                        visualStyle->SetAttribute("displayFlags",oss.str());
                    }
                }
                else
                {
                    if( (visualStyle = v_nodes.rootNode()->FirstChildElement("VisualStyle")) != NULL )
                    {
                        v_nodes.rootNode()->RemoveChild(visualStyle);
                    }
                }
            }
        }

        doc->Print();
        std::cout.flush();
        delete doc;
    }
    else
    {
        return -1;
    }

    sofa::core::cleanup();
    return retValue;
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
  double myJoints[ROBOT_DOF] = {1,2,3,4,5,6};
  double jointsIn[ROBOT_DOF];
  robotPose myPose, poseIn;
  int kukaConnection;
  RCS_TIMER *cycleBlock = new RCS_TIMER(KUKA_DEFAULT_CYCLE);
  TiXmlDocument kukaStatus;
  TiXmlHandle toSendHandle(&kukaStatus);
  TiXmlElement *cartesianStatus;
  TiXmlElement *cartesianUpdate;
  TiXmlElement *jointStatus;
  TiXmlElement *jointUpdate;
  TiXmlElement *IPOCUpdate;
  int nchars;
  TiXmlElement *cartesian;
  int debug = 0;
  int option;
  int counter = 0;
  double jointMotorScale[ROBOT_DOF], cmdMotorScale[ROBOT_DOF];

  jointMotorScale[0] = 80.;
  jointMotorScale[1] = 100.;
  jointMotorScale[2] = 80.;
  jointMotorScale[3] = 80.;
  jointMotorScale[4] = 80.;
  jointMotorScale[5] = 40.5;

  cmdMotorScale[0] = 1.4;
  cmdMotorScale[1] = 1.74;
  cmdMotorScale[2] = 1.4;
  cmdMotorScale[3] = 1.4;
  cmdMotorScale[4] = 1.4;
  cmdMotorScale[5] = 0.87;

  while (true) 
    {
      option = getopt(argc, argv, ":d");
      if (option == -1) break;
      switch (option) 
	{
	case 'd':
	  debug = 1;
	  break;
	case ':':
	  fprintf(stderr, "missing value for -%c\n", optopt);
	  return 1;
	  break;
	default:
	  fprintf (stderr, "unrecognized option -%c\n", optopt);
	  return 1;
	  break;
	} // switch (option)
    }   // while (true) for getopt


  if( !kukaStatus.LoadFile(DEFAULT_FROM_KUKA))
    {
      printf( "kukaRobot:: fatal error on load of %s\n", DEFAULT_FROM_KUKA);
      exit(1);
    }
  kukaConnection = ulapi_socket_get_client_id(KUKA_PORT, "localhost");
  if( kukaConnection < 0 )
    return -1;

  myPose.x = 0.1;
  myPose.y = 0.2;
  myPose.z = 0.3;
  myPose.xrot = 0.4;
  myPose.yrot = 0.5;
  myPose.zrot = 0.6;

  while(true)
    {
      TiXmlDocument kukaCorrections;
      TiXmlHandle correctionsHandle(&kukaCorrections);
      std::string str;
      enum {INBUF_LEN = 2048};
      char inbuf[INBUF_LEN];
      std::ostringstream s;
      cartesianStatus =
	toSendHandle.FirstChild("Rob").FirstChild("Dat").Child(1).ToElement();
      IPOCUpdate = toSendHandle.FirstChild("Rob").FirstChild("Dat").Child(9).
	ToElement();
      jointStatus =
	toSendHandle.FirstChild("Rob").FirstChild("Dat").Child(3).ToElement();
      cartesianStatus->SetDoubleAttribute("X", myPose.x); 
      cartesianStatus->SetDoubleAttribute ("Y", myPose.y);
      cartesianStatus->SetDoubleAttribute ("Z", myPose.z);
      cartesianStatus->SetDoubleAttribute ("A", myPose.xrot);
      cartesianStatus->SetDoubleAttribute ("B", myPose.yrot);
      cartesianStatus->SetDoubleAttribute ("C", myPose.zrot);
      jointStatus->SetDoubleAttribute("A1", myJoints[0]);
      jointStatus->SetDoubleAttribute("A2", myJoints[1]);
      jointStatus->SetDoubleAttribute("A3", myJoints[2]);
      jointStatus->SetDoubleAttribute("A4", myJoints[3]);
      jointStatus->SetDoubleAttribute("A5", myJoints[4]);
      jointStatus->SetDoubleAttribute("A6", myJoints[5]);

      s << counter++;
      s << '\0';
      TiXmlText *text = new TiXmlText((s.str()).c_str());
      IPOCUpdate->Clear();
      IPOCUpdate->LinkEndChild(text);
      //      kukaStatus.Print();
      str << kukaStatus;
      ulapi_socket_write(kukaConnection, str.c_str(), str.length());
      inbuf[0] = '\0';
      nchars = ulapi_socket_read(kukaConnection, inbuf, sizeof(inbuf)-1);
      if (nchars <= 0) 
	{
	  printf("kukaRobot::status client disconnected\n");
	  break;
	}
      else
	{
	inbuf[nchars] = '\0';
	}
      kukaCorrections.Parse(inbuf);
      if(debug) kukaCorrections.Print();
      cartesianUpdate =
	correctionsHandle.FirstChild("Sen").FirstChild("Dat").
	Child(1).ToElement();
      jointUpdate =
	correctionsHandle.FirstChild("Sen").FirstChild("Dat").
	Child(2).ToElement();
      cartesianUpdate->QueryDoubleAttribute("X", &(poseIn.x));
      cartesianUpdate->QueryDoubleAttribute("Y", &(poseIn.y));
      cartesianUpdate->QueryDoubleAttribute("Z", &(poseIn.z));
      cartesianUpdate->QueryDoubleAttribute("A", &(poseIn.xrot));
      cartesianUpdate->QueryDoubleAttribute("B", &(poseIn.yrot));
      cartesianUpdate->QueryDoubleAttribute("C", &(poseIn.zrot));
      jointUpdate->QueryDoubleAttribute("A1", &(jointsIn[0]));
      jointUpdate->QueryDoubleAttribute("A2", &(jointsIn[1]));
      jointUpdate->QueryDoubleAttribute("A3", &(jointsIn[2]));
      jointUpdate->QueryDoubleAttribute("A4", &(jointsIn[3]));
      jointUpdate->QueryDoubleAttribute("A5", &(jointsIn[4]));
      jointUpdate->QueryDoubleAttribute("A6", &(jointsIn[5]));
      myPose.x += poseIn.x;
      myPose.y += poseIn.y;
      myPose.z += poseIn.z;
      myPose.xrot += poseIn.xrot;
      myPose.yrot += poseIn.yrot;
      myPose.zrot += poseIn.zrot;
      for( int i=0; i<ROBOT_DOF; i++ )
	{
	  myJoints[i] += jointsIn[i] * cmdMotorScale[i] / jointMotorScale[i];
	  if( debug )
	    printf( "J%d <%lf %lf> ", i+1, myJoints[i], jointsIn[i] );
	}
      if(debug)
      printf( "\nkukaRobot Status: <%4.2f, %4.2f, %4.2f> <%4.2f, %4.2f, %4.2f>\n\n",
	      myPose.x,
	      myPose.y,
	      myPose.z,
	      myPose.xrot,
	      myPose.yrot,
	      myPose.zrot);
      cycleBlock->wait();
    }
}
Exemplo n.º 12
0
//================================================================================================
//
//  Save()
//
//    - Called by ???
//
/// <summary>
///   Writes out currently-set config to peerblock.conf file.
/// </summary>
//
void Configuration::Save(const TCHAR * _filename)
{
    TRACEI("[Configuration] [Save]  > Entering routine.");

    if (TempAllowingHttpShort || TempAllowingHttpLong)
        SetBlockHttp(this->PortSet.AllowHttp);	// make sure we don't accidentally startup allowed

    TiXmlDocument doc;
    doc.InsertEndChild(TiXmlDeclaration("1.0", "UTF-8", "yes"));

    TiXmlElement *root=InsertChild(&doc, "PeerBlock");

    {
        TiXmlElement *settings=InsertChild(root, "Settings");

        InsertChild(settings, "AllowLocal", this->AllowLocal);
        InsertChild(settings, "CacheCrc", this->CacheCrc);
        InsertChild(settings, "BlinkOnBlock", this->BlinkOnBlock);
        InsertChild(settings, "NotifyOnBlock", this->NotifyOnBlock);
        InsertChild(settings, "LastVersionRun", PB_VER_BUILDNUM);
        InsertChild(settings, "RecentBlockWarntime", (int)this->RecentBlockWarntime);
        InsertChild(settings, "ListSanityChecking", this->EnableListSanityChecking);
        InsertChild(settings, "WarningIconForHttpAllow", this->EnableWarningIconForHttpAllow);
    }

    {
        TiXmlElement *logging=InsertChild(root, "Logging");

        InsertChild(logging, "LogSize", this->LogSize);
        InsertChild(logging, "LogAllowed", this->LogAllowed);
        InsertChild(logging, "LogBlocked", this->LogBlocked);
        InsertChild(logging, "ShowAllowed", this->ShowAllowed);

        {
            TiXmlElement *e=InsertChild(logging, "Cleanup", this->CleanupType);
            e->SetAttribute("Interval", (int)this->CleanupInterval);
        }

        InsertChild(logging, "ArchivePath", this->ArchivePath.directory_str());

        InsertChild(logging, "MaxHistorySize", this->MaxHistorySize);

        InsertChild(logging, "HistoryCheckInterval", this->HistoryCheckInterval);
    }

    {
        TiXmlElement *logging=InsertChild(root, "TraceLog");

        InsertChild(logging, "Enabled", this->TracelogEnabled);
        InsertChild(logging, "Level", this->TracelogLevel);
    }

    {
        TiXmlElement *colors=InsertChild(root, "Colors");

        InsertChild(colors, "ColorCode", this->ColorCode);
        InsertChild(colors, "Blocked", this->BlockedColor);
        InsertChild(colors, "Allowed", this->AllowedColor);
        InsertChild(colors, "Http", this->HttpColor);
    }

    {
        TiXmlElement *windowing=InsertChild(root, "Windowing");

        if(RectValid(this->WindowPos))
            InsertChild(windowing, "Main", this->WindowPos);

        if(RectValid(this->UpdateWindowPos))
            InsertChild(windowing, "Update", this->UpdateWindowPos);

        if(RectValid(this->ListManagerWindowPos))
            InsertChild(windowing, "ListManager", this->ListManagerWindowPos);

        if(RectValid(this->ListEditorWindowPos))
            InsertChild(windowing, "ListEditor", this->ListEditorWindowPos);

        if(RectValid(this->HistoryWindowPos))
            InsertChild(windowing, "History", this->HistoryWindowPos);

        InsertChild(windowing, "StartMinimized", this->StartMinimized);
        InsertChild(windowing, "ShowSplash", this->ShowSplash);
        InsertChild(windowing, "StayHidden", this->StayHidden);
        InsertChild(windowing, "HideOnClose", this->HideOnClose);

        InsertChild(windowing, "HideMain", this->WindowHidden);
        InsertChild(windowing, "AlwaysOnTop", this->AlwaysOnTop);
        InsertChild(windowing, "HideTrayIcon", this->HideTrayIcon);

        {
            TiXmlElement *hcol=InsertChild(windowing, "HistoryColumns");

            InsertChild(hcol, "Time", this->HistoryColumns[0]);
            InsertChild(hcol, "Range", this->HistoryColumns[1]);
            InsertChild(hcol, "Source", this->HistoryColumns[2]);
            InsertChild(hcol, "Destination", this->HistoryColumns[3]);
            InsertChild(hcol, "Protocol", this->HistoryColumns[4]);
            InsertChild(hcol, "Action", this->HistoryColumns[5]);
        }

        {
            TiXmlElement *lcol=InsertChild(windowing, "LogColumns");

            InsertChild(lcol, "Time", this->LogColumns[0]);
            InsertChild(lcol, "Range", this->LogColumns[1]);
            InsertChild(lcol, "Source", this->LogColumns[2]);
            InsertChild(lcol, "Destination", this->LogColumns[3]);
            InsertChild(lcol, "Protocol", this->LogColumns[4]);
            InsertChild(lcol, "Action", this->LogColumns[5]);
        }

        {
            TiXmlElement *lcol=InsertChild(windowing, "ListEditorColumns");

            InsertChild(lcol, "Range", this->ListEditorColumns[0]);
            InsertChild(lcol, "StartingIp", this->ListEditorColumns[1]);
            InsertChild(lcol, "EndingIp", this->ListEditorColumns[2]);
        }

        {
            TiXmlElement *lcol=InsertChild(windowing, "ListManagerColumns");

            InsertChild(lcol, "File", this->ListManagerColumns[0]);
            InsertChild(lcol, "Type", this->ListManagerColumns[1]);
            InsertChild(lcol, "Description", this->ListManagerColumns[2]);
        }

        {
            TiXmlElement *ucol=InsertChild(windowing, "UpdateColumns");

            InsertChild(ucol, "Description", this->UpdateColumns[0]);
            InsertChild(ucol, "Task", this->UpdateColumns[1]);
            InsertChild(ucol, "Status", this->UpdateColumns[2]);
        }
    }

    {
        TiXmlElement *updates=InsertChild(root, "Updates");

        InsertChild(updates, "UpdatePeerBlock", this->UpdatePeerBlock);
        InsertChild(updates, "UpdateLists", this->UpdateLists);
        InsertChild(updates, "UpdateAtStartup", this->UpdateAtStartup);
        InsertChild(updates, "UpdateInterval", this->UpdateInterval);
        InsertChild(updates, "UpdateCountdown", this->UpdateCountdown);
        InsertChild(updates, "IgnoreListUpdateLimit", this->IgnoreListUpdateLimit);
        InsertChild(updates, "UniqueId", this->UniqueId);

        {
            TiXmlElement *proxy=InsertChild(updates, "UpdateProxy", this->UpdateProxy);
            proxy->SetAttribute("Type", (this->UpdateProxyType==CURLPROXY_HTTP)?"http":"socks5");
        }

        TiXmlElement *lastupdate=InsertChild(updates, "LastUpdate");
        if(this->LastUpdate) {
            string t=boost::lexical_cast<string>((int)this->LastUpdate);
            lastupdate->InsertEndChild(TiXmlText(t));
        }

        TiXmlElement *lastarchived=InsertChild(updates, "LastArchived");
        if(this->LastArchived) {
            string t=boost::lexical_cast<string>((int)this->LastArchived);
            lastarchived->InsertEndChild(TiXmlText(t));
        }

        TiXmlElement *laststarted=InsertChild(updates, "LastStarted");
        if(this->LastStarted) {
            string t=boost::lexical_cast<string>((int)this->LastStarted);
            laststarted->InsertEndChild(TiXmlText(t));
        }
    }

    {
        TiXmlElement *messages=InsertChild(root, "Messages");

        InsertChild(messages, "FirstBlock", this->FirstBlock);
        InsertChild(messages, "FirstHide", this->FirstHide);
    }

    {
        TiXmlElement *portset = InsertChild(root, "PortSet");

        InsertChild(portset, "AllowHttp", this->PortSet.AllowHttp);
        InsertChild(portset, "AllowFtp", this->PortSet.AllowFtp);
        InsertChild(portset, "AllowSmtp", this->PortSet.AllowSmtp);
        InsertChild(portset, "AllowPop3", this->PortSet.AllowPop3);

        TiXmlElement *profiles = InsertChild(portset, "Profiles");
        for (vector<PortProfile>::const_iterator pfit = this->PortSet.Profiles.begin(); pfit != this->PortSet.Profiles.end(); ++pfit) {
            TiXmlElement *profile = InsertChild(profiles, "Profile");

            PortProfile pf = (PortProfile) *pfit;

            InsertChild(profile, "Name", pf.Name);
            InsertChild(profile, "Enabled", pf.Enabled);
            InsertChild(profile, "Type", pf.Type);

            TiXmlElement *ports = InsertChild(profile, "Ports");
            for (vector<PortRange>::const_iterator pit = pf.Ports.begin(); pit != pf.Ports.end(); ++pit) {
                TiXmlElement *range = InsertChild(ports, "Range");
                InsertAttribute(range, (PortRange) *pit);
            }
        }
    }

    {
        TiXmlElement *lists=InsertChild(root, "Lists");

        for(vector<StaticList>::size_type i=0; i<this->StaticLists.size(); i++) {
            TiXmlElement *list=InsertChild(lists, "List");

            InsertChild(list, "File", TSTRING_UTF8(this->StaticLists[i].File.file_str()));
            InsertChild(list, "Type", (this->StaticLists[i].Type==List::Allow)?"allow":"block");
            InsertChild(list, "Description", this->StaticLists[i].Description);
            InsertChild(list, "Enabled", this->StaticLists[i].Enabled);
        }

        for(vector<DynamicList>::size_type i=0; i<this->DynamicLists.size(); i++) {
            TiXmlElement *list=InsertChild(lists, "List");

            InsertChild(list, "Url", this->DynamicLists[i].Url);
            InsertChild(list, "Type", (this->DynamicLists[i].Type==List::Allow)?"allow":"block");
            InsertChild(list, "Description", this->DynamicLists[i].Description);
            InsertChild(list, "Enabled", this->DynamicLists[i].Enabled);
            InsertChild(list, "FailedUpdate", this->DynamicLists[i].FailedUpdate);

            TiXmlElement *lastupdate=InsertChild(list, "LastUpdate");
            if(this->DynamicLists[i].LastUpdate) {
                string s=boost::lexical_cast<string>((int)this->DynamicLists[i].LastUpdate);
                lastupdate->InsertEndChild(TiXmlText(s));
            }

            TiXmlElement *lastdownload=InsertChild(list, "LastDownload");
            if(this->DynamicLists[i].LastDownload) {
                string s=boost::lexical_cast<string>((int)this->DynamicLists[i].LastDownload);
                lastdownload->InsertEndChild(TiXmlText(s));
            }
        }
    }

    {
        TiXmlElement *ibl=InsertChild(root, "I-Blocklist");

        InsertChild(ibl, "Username", this->IblUsername);
        InsertChild(ibl, "PIN", this->IblPin);
    }

    // First save to a temp-file
    std::wstring tempfile = _filename;
    tempfile += L".tmp";
    FILE *fp=_tfopen((path::base_dir()/tempfile.c_str()).file_str().c_str(), _T("w"));
    if(!fp)
    {
        TRACEERR("[Configuration] [Save]", L"Can't open file", GetLastError());
        throw runtime_error("unable to save configuration");
    }
    {
        boost::shared_ptr<void> ptr(fp, fclose);
        doc.Print(fp);
    }

    // Now, only after that's done should we overwrite the original
    path::move((path::base_dir()/tempfile.c_str()), (path::base_dir()/_filename), true);

    TRACEI("[Configuration] [Save]  < Leaving routine.");

} // End of Save()