示例#1
0
const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
	p = SkipWhiteSpace( p, encoding );
	TiXmlDocument* document = GetDocument();

	if ( !p || !*p )
	{
		if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding );
		return 0;
	}

	if ( data )
	{
		data->Stamp( p, encoding );
		location = data->Cursor();
	}

	if ( *p != '<' )
	{
		if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding );
		return 0;
	}

	p = SkipWhiteSpace( p+1, encoding );

	// Read the name.
	const char* pErr = p;

    p = ReadName( p, &value, encoding );
	if ( !p || !*p )
	{
		if ( document )	document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding );
		return 0;
	}

    TIXML_STRING endTag ("</");
	endTag += value;
	endTag += ">";

	// Check for and read attributes. Also look for an empty
	// tag or an end tag.
	while ( p && *p )
	{
		pErr = p;
		p = SkipWhiteSpace( p, encoding );
		if ( !p || !*p )
		{
			if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding );
			return 0;
		}
		if ( *p == '/' )
		{
			++p;
			// Empty tag.
			if ( *p  != '>' )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding );		
				return 0;
			}
			return (p+1);
		}
		else if ( *p == '>' )
		{
			// Done with attributes (if there were any.)
			// Read the value -- which can include other
			// elements -- read the end tag, and return.
			++p;
			p = ReadValue( p, data, encoding );		// Note this is an Element method, and will set the error if one happens.
			if ( !p || !*p )
				return 0;

			// We should find the end tag now
			if ( StringEqual( p, endTag.c_str(), false, encoding ) )
			{
				p += endTag.length();
				return p;
			}
			else
			{
				if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
				return 0;
			}
		}
		else
		{
			// Try to read an attribute:
			TiXmlAttribute* attrib = new TiXmlAttribute();
			if ( !attrib )
			{
				if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, pErr, data, encoding );
				return 0;
			}

			attrib->SetDocument( document );
			const char* pErr = p;
			p = attrib->Parse( p, data, encoding );

			if ( !p || !*p )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding );
				delete attrib;
				return 0;
			}

			// Handle the strange case of double attributes:
			TiXmlAttribute* node = attributeSet.Find( attrib->NameTStr() );
			if ( node )
			{
				node->SetValue( attrib->Value() );
				delete attrib;
				return 0;
			}

			attributeSet.Add( attrib );
		}
	}
	return p;
}
示例#2
0
void TiXmlElement::StreamIn (TIXML_ISTREAM * in, TIXML_STRING * tag)
{
	// We're called with some amount of pre-parsing. That is, some of "this"
	// element is in "tag". Go ahead and stream to the closing ">"
	while( in->good() )
	{
		int c = in->get();
		if ( c <= 0 )
		{
			TiXmlDocument* document = GetDocument();
			if ( document )
				document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
			return;
		}
		(*tag) += (char) c ;
		
		if ( c == '>' )
			break;
	}

	if ( tag->length() < 3 ) return;

	// Okay...if we are a "/>" tag, then we're done. We've read a complete tag.
	// If not, identify and stream.

	if (    tag->at( tag->length() - 1 ) == '>' 
		 && tag->at( tag->length() - 2 ) == '/' )
	{
		// All good!
		return;
	}
	else if ( tag->at( tag->length() - 1 ) == '>' )
	{
		// There is more. Could be:
		//		text
		//		closing tag
		//		another node.
		for ( ;; )
		{
			StreamWhiteSpace( in, tag );

			// Do we have text?
			if ( in->good() && in->peek() != '<' ) 
			{
				// Yep, text.
				TiXmlText text( "" );
				text.StreamIn( in, tag );

				// What follows text is a closing tag or another node.
				// Go around again and figure it out.
				continue;
			}

			// We now have either a closing tag...or another node.
			// We should be at a "<", regardless.
			if ( !in->good() ) return;
			assert( in->peek() == '<' );
			int tagIndex = tag->length();

			bool closingTag = false;
			bool firstCharFound = false;

			for( ;; )
			{
				if ( !in->good() )
					return;

				int c = in->peek();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				
				if ( c == '>' )
					break;

				*tag += (char) c;
				in->get();

				if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) )
				{
					firstCharFound = true;
					if ( c == '/' )
						closingTag = true;
				}
			}
			// If it was a closing tag, then read in the closing '>' to clean up the input stream.
			// If it was not, the streaming will be done by the tag.
			if ( closingTag )
			{
				if ( !in->good() )
					return;

				int c = in->get();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				assert( c == '>' );
				*tag += (char) c;

				// We are done, once we've found our closing tag.
				return;
			}
			else
			{
				// If not a closing tag, id it, and stream.
				const char* tagloc = tag->c_str() + tagIndex;
				TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING );
				if ( !node )
					return;
				node->StreamIn( in, tag );
				delete node;
				node = 0;

				// No return: go around from the beginning: text, closing tag, or node.
			}
		}
	}
}
示例#3
0
	void Map::ParseText(const string &text) 
	{
		// Create a tiny xml document and use it to parse the text.
		TiXmlDocument doc;
		doc.Parse(text.c_str());
	
		// Check for parsing errors.
		if (doc.Error()) 
		{
			has_error = true;
			error_code = TMX_PARSING_ERROR;
			error_text = doc.ErrorDesc();
			return;
		}

		TiXmlNode *mapNode = doc.FirstChild("map");
		TiXmlElement* mapElem = mapNode->ToElement();

		// Read the map attributes.
		mapElem->Attribute("version", &version);
		mapElem->Attribute("width", &width);
		mapElem->Attribute("height", &height);
		mapElem->Attribute("tilewidth", &tile_width);
		mapElem->Attribute("tileheight", &tile_height);

		// Read the orientation
		std::string orientationStr = mapElem->Attribute("orientation");

		if (!orientationStr.compare("orthogonal")) 
		{
			orientation = TMX_MO_ORTHOGONAL;
		} 
		else if (!orientationStr.compare("isometric")) 
		{
			orientation = TMX_MO_ISOMETRIC;
		}
		else if (!orientationStr.compare("staggered")) 
		{
			orientation = TMX_MO_STAGGERED;
		}
		

		const TiXmlNode *node = mapElem->FirstChild();
		int zOrder = 0;
		while( node )
		{
			// Read the map properties.
			if( strcmp( node->Value(), "properties" ) == 0 )
			{
				properties.Parse(node);			
			}

			// Iterate through all of the tileset elements.
			if( strcmp( node->Value(), "tileset" ) == 0 )
			{
				// Allocate a new tileset and parse it.
				Tileset *tileset = new Tileset();
				tileset->Parse(node->ToElement());

				// Add the tileset to the list.
				tilesets.push_back(tileset);
			}

			// Iterate through all of the layer elements.			
			if( strcmp( node->Value(), "layer" ) == 0 )
			{
				// Allocate a new layer and parse it.
				Layer *layer = new Layer(this);
				layer->Parse(node);
				layer->SetZOrder( zOrder );
				++zOrder;

				// Add the layer to the list.
				layers.push_back(layer);
			}

			// Iterate through all of the imagen layer elements.			
			if( strcmp( node->Value(), "imagelayer" ) == 0 )
			{
				// Allocate a new layer and parse it.
				ImageLayer *imageLayer = new ImageLayer(this);
				imageLayer->Parse(node);
				imageLayer->SetZOrder( zOrder );
				++zOrder;

				// Add the layer to the list.
				image_layers.push_back(imageLayer);
			}

			// Iterate through all of the objectgroup elements.
			if( strcmp( node->Value(), "objectgroup" ) == 0 )
			{
				// Allocate a new object group and parse it.
				ObjectGroup *objectGroup = new ObjectGroup();
				objectGroup->Parse(node);
				objectGroup->SetZOrder( zOrder );
				++zOrder;
		
				// Add the object group to the list.
				object_groups.push_back(objectGroup);
			}

			node = node->NextSibling();
		}
	}
示例#4
0
const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
	TiXmlDocument* document = GetDocument();

	const char* pWithWhiteSpace = p;
	// Read in text and elements in any order.
	p = SkipWhiteSpace( p, encoding );
	while ( p && *p )
	{
		if ( *p != '<' )
		{
			// Take what we have, make a text element.
			TiXmlText* textNode = new TiXmlText( "" );

			if ( !textNode )
			{
				if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding );
				    return 0;
			}

			if ( TiXmlBase::IsWhiteSpaceCondensed() )
			{
				p = textNode->Parse( p, data, encoding );
			}
			else
			{
				// Special case: we want to keep the white space
				// so that leading spaces aren't removed.
				p = textNode->Parse( pWithWhiteSpace, data, encoding );
			}

			if ( !textNode->Blank() )
				LinkEndChild( textNode );
			else
				delete textNode;
		} 
		else 
		{
			// We hit a '<'
			// Have we hit a new element or an end tag?
			if ( StringEqual( p, "</", false, encoding ) )
			{
				return p;
			}
			else
			{
				TiXmlNode* node = Identify( p, encoding );
				if ( node )
				{
					p = node->Parse( p, data, encoding );
					LinkEndChild( node );
				}				
				else
				{
					return 0;
				}
			}
		}
		p = SkipWhiteSpace( p, encoding );
	}

	if ( !p )
	{
		if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding );
	}	
	return p;
}
示例#5
0
TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding )
{
	TiXmlNode* returnNode = 0;

	p = SkipWhiteSpace( p, encoding );
	if( !p || !*p || *p != '<' )
	{
		return 0;
	}

	TiXmlDocument* doc = GetDocument();
	p = SkipWhiteSpace( p, encoding );

	if ( !p || !*p )
	{
		return 0;
	}

	// What is this thing? 
	// - Elements start with a letter or underscore, but xml is reserved.
	// - Comments: <!--
	// - Decleration: <?xml
	// - Everthing else is unknown to tinyxml.
	//

	const char* xmlHeader = { "<?xml" };
	const char* commentHeader = { "<!--" };
	const char* dtdHeader = { "<!" };

	if ( StringEqual( p, xmlHeader, true, encoding ) )
	{
		#ifdef DEBUG_PARSER
			TIXML_LOG( "XML parsing Declaration\n" );
		#endif
		returnNode = new TiXmlDeclaration();
	}
	else if ( StringEqual( p, commentHeader, false, encoding ) )
	{
		#ifdef DEBUG_PARSER
			TIXML_LOG( "XML parsing Comment\n" );
		#endif
		returnNode = new TiXmlComment();
	}
	else if ( StringEqual( p, dtdHeader, false, encoding ) )
	{
		#ifdef DEBUG_PARSER
			TIXML_LOG( "XML parsing Unknown(1)\n" );
		#endif
		returnNode = new TiXmlUnknown();
	}
	else if (    IsAlpha( *(p+1), encoding )
			  || *(p+1) == '_' )
	{
		#ifdef DEBUG_PARSER
			TIXML_LOG( "XML parsing Element\n" );
		#endif
		returnNode = new TiXmlElement( "" );
	}
	else
	{
		#ifdef DEBUG_PARSER
			TIXML_LOG( "XML parsing Unknown(2)\n" );
		#endif
		returnNode = new TiXmlUnknown();
	}

	if ( returnNode )
	{
		// Set the parent, so it can report errors
		returnNode->parent = this;
	}
	else
	{
		if ( doc )
			doc->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );
	}
	return returnNode;
}
int PluginsManager::loadPlugin(const TCHAR *pluginFilePath, vector<generic_string> & dll2Remove)
{
	const TCHAR *pluginFileName = ::PathFindFileName(pluginFilePath);
	if (isInLoadedDlls(pluginFileName))
		return 0;

	PluginInfo *pi = new PluginInfo;
	try
	{
		pi->_moduleName = PathFindFileName(pluginFilePath);

		pi->_hLib = ::LoadLibrary(pluginFilePath);
		if (!pi->_hLib)
			throw generic_string(TEXT("Load Library is failed.\nMake \"Runtime Library\" setting of this project as \"Multi-threaded(/MT)\" may cure this problem."));

		pi->_pFuncIsUnicode = (PFUNCISUNICODE)GetProcAddress(pi->_hLib, "isUnicode");
		if (!pi->_pFuncIsUnicode || !pi->_pFuncIsUnicode())
			throw generic_string(TEXT("This ANSI plugin is not compatible with your Unicode Notepad++."));

		pi->_pFuncSetInfo = (PFUNCSETINFO)GetProcAddress(pi->_hLib, "setInfo");

		if (!pi->_pFuncSetInfo)
			throw generic_string(TEXT("Missing \"setInfo\" function"));

		pi->_pFuncGetName = (PFUNCGETNAME)GetProcAddress(pi->_hLib, "getName");
		if (!pi->_pFuncGetName)
			throw generic_string(TEXT("Missing \"getName\" function"));

		pi->_pBeNotified = (PBENOTIFIED)GetProcAddress(pi->_hLib, "beNotified");
		if (!pi->_pBeNotified)
			throw generic_string(TEXT("Missing \"beNotified\" function"));

		pi->_pMessageProc = (PMESSAGEPROC)GetProcAddress(pi->_hLib, "messageProc");
		if (!pi->_pMessageProc)
			throw generic_string(TEXT("Missing \"messageProc\" function"));

		pi->_pFuncSetInfo(_nppData);

		pi->_pFuncGetFuncsArray = (PFUNCGETFUNCSARRAY)GetProcAddress(pi->_hLib, "getFuncsArray");
		if (!pi->_pFuncGetFuncsArray)
			throw generic_string(TEXT("Missing \"getFuncsArray\" function"));

		pi->_funcItems = pi->_pFuncGetFuncsArray(&pi->_nbFuncItem);

		if ((!pi->_funcItems) || (pi->_nbFuncItem <= 0))
			throw generic_string(TEXT("Missing \"FuncItems\" array, or the nb of Function Item is not set correctly"));

		pi->_pluginMenu = ::CreateMenu();

		GetLexerCountFn GetLexerCount = (GetLexerCountFn)::GetProcAddress(pi->_hLib, "GetLexerCount");
		// it's a lexer plugin
		if (GetLexerCount)
		{
			GetLexerNameFn GetLexerName = (GetLexerNameFn)::GetProcAddress(pi->_hLib, "GetLexerName");
			if (!GetLexerName)
				throw generic_string(TEXT("Loading GetLexerName function failed."));

			GetLexerStatusTextFn GetLexerStatusText = (GetLexerStatusTextFn)::GetProcAddress(pi->_hLib, "GetLexerStatusText");

			if (!GetLexerStatusText)
				throw generic_string(TEXT("Loading GetLexerStatusText function failed."));

			// Assign a buffer for the lexer name.
			char lexName[MAX_EXTERNAL_LEXER_NAME_LEN];
			lexName[0] = '\0';
			TCHAR lexDesc[MAX_EXTERNAL_LEXER_DESC_LEN];
			lexDesc[0] = '\0';

			int numLexers = GetLexerCount();

			NppParameters * nppParams = NppParameters::getInstance();

			ExternalLangContainer *containers[30];

			WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
			for (int x = 0; x < numLexers; ++x)
			{
				GetLexerName(x, lexName, MAX_EXTERNAL_LEXER_NAME_LEN);
				GetLexerStatusText(x, lexDesc, MAX_EXTERNAL_LEXER_DESC_LEN);
				const TCHAR *pLexerName = wmc->char2wchar(lexName, CP_ACP);
				if (!nppParams->isExistingExternalLangName(pLexerName) && nppParams->ExternalLangHasRoom())
					containers[x] = new ExternalLangContainer(pLexerName, lexDesc);
				else
					containers[x] = NULL;
			}

			TCHAR xmlPath[MAX_PATH];
            lstrcpy(xmlPath, nppParams->getNppPath().c_str());
			PathAppend(xmlPath, TEXT("plugins\\Config"));
            PathAppend(xmlPath, pi->_moduleName.c_str());
			PathRemoveExtension(xmlPath);
			PathAddExtension(xmlPath, TEXT(".xml"));

			if (!PathFileExists(xmlPath))
			{
				lstrcpyn(xmlPath, TEXT("\0"), MAX_PATH );
				lstrcpy(xmlPath, nppParams->getAppDataNppDir() );
				PathAppend(xmlPath, TEXT("plugins\\Config"));
                PathAppend(xmlPath, pi->_moduleName.c_str());
				PathRemoveExtension( xmlPath );
				PathAddExtension( xmlPath, TEXT(".xml") );

				if (! PathFileExists( xmlPath ) )
				{
					throw generic_string(generic_string(xmlPath) + TEXT(" is missing."));
				}
			}

			TiXmlDocument *pXmlDoc = new TiXmlDocument(xmlPath);

			if (!pXmlDoc->LoadFile())
			{
				delete pXmlDoc;
				pXmlDoc = NULL;
				throw generic_string(generic_string(xmlPath) + TEXT(" failed to load."));
			}

			for (int x = 0; x < numLexers; ++x) // postpone adding in case the xml is missing/corrupt
			{
				if (containers[x] != NULL)
					nppParams->addExternalLangToEnd(containers[x]);
			}

			nppParams->getExternalLexerFromXmlTree(pXmlDoc);
			nppParams->getExternalLexerDoc()->push_back(pXmlDoc);
			const char *pDllName = wmc->wchar2char(pluginFilePath, CP_ACP);
			::SendMessage(_nppData._scintillaMainHandle, SCI_LOADLEXERLIBRARY, 0, (LPARAM)pDllName);

		}
		addInLoadedDlls(pluginFileName);
		_pluginInfos.push_back(pi);
        return (_pluginInfos.size() - 1);
	}
	catch (std::exception e)
	{
		::MessageBoxA(NULL, e.what(), "Exception", MB_OK);
		return -1;
	}
	catch (generic_string s)
	{
		s += TEXT("\n\n");
		s += USERMSG;
		if (::MessageBox(NULL, s.c_str(), pluginFilePath, MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
	catch (...)
	{
		generic_string msg = TEXT("Failed to load");
		msg += TEXT("\n\n");
		msg += USERMSG;
		if (::MessageBox(NULL, msg.c_str(), pluginFilePath, MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
}
示例#7
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 =   "\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( "utf8testout.xml", "r" );
            FILE* verify = fopen( "utf8testverify.xml", "r" );
            if ( saved && verify )
            {
                while ( fgets( verifyBuf, 256, verify ) )
                {
                    fgets( savedBuf, 256, saved );
                    if ( strcmp( verifyBuf, savedBuf ) )
                    {
                        okay = 0;
                        break;
                    }
                }
                fclose( saved );
                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.", 0, (int)doc.Error() ); // not an  error to tinyxml
        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?nt?nt???????"
                        "</?>";

            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?nt?nt???????", 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( "<tag>/</tag>" );
        xml.Print();
        xml.FirstChild()->Print( stdout, 0 );
        xml.FirstChild()->Type();
    }
    */

    /*  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;
}
示例#8
0
void CMusicInfoScraper::FindAlbuminfo()
{
  CStdString strAlbum=m_strAlbum;
  CStdString strHTML;
  m_vecAlbums.erase(m_vecAlbums.begin(), m_vecAlbums.end());

  CScraperParser parser;
  if (!parser.Load(_P("q:\\system\\scrapers\\music\\"+m_info.strPath)))
    return;

  if (!m_info.settings.GetPluginRoot() || m_info.settings.GetSettings().IsEmpty())
  {
    m_info.settings.LoadSettingsXML(_P("q:\\system\\scrapers\\music\\"+m_info.strPath));
    m_info.settings.SaveFromDefault();
  }

  parser.m_param[0] = strAlbum;
  parser.m_param[1] = m_strArtist;
  CUtil::URLEncode(parser.m_param[0]);
  CUtil::URLEncode(parser.m_param[1]);

  CScraperUrl scrURL;
  scrURL.ParseString(parser.Parse("CreateAlbumSearchUrl"));
  if (!CScraperUrl::Get(scrURL.m_url[0], strHTML, m_http) || strHTML.size() == 0)
  {
    CLog::Log(LOGERROR, "%s: Unable to retrieve web site",__FUNCTION__);
    return;
  }

  parser.m_param[0] = strHTML;
  CStdString strXML = parser.Parse("GetAlbumSearchResults",&m_info.settings);
  if (strXML.IsEmpty())
  {
    CLog::Log(LOGERROR, "%s: Unable to parse web site",__FUNCTION__);
    return;
  }

  if (strXML.Find("encoding=\"utf-8\"") < 0)
    g_charsetConverter.stringCharsetToUtf8(strXML);

  // ok, now parse the xml file
  TiXmlDocument doc;
  doc.Parse(strXML.c_str(),0,TIXML_ENCODING_UTF8);
  if (!doc.RootElement())
  {
    CLog::Log(LOGERROR, "%s: Unable to parse xml",__FUNCTION__);
    return;
  }
  TiXmlHandle docHandle( &doc );
  TiXmlElement* album = docHandle.FirstChild( "results" ).FirstChild( "entity" ).Element();
  if (!album)
    return;

  while (album)
  {
    TiXmlNode* title = album->FirstChild("title");
    TiXmlElement* link = album->FirstChildElement("url");
    TiXmlNode* artist = album->FirstChild("artist");
    TiXmlNode* year = album->FirstChild("year");
    if (title && title->FirstChild())
    {
      CStdString strTitle = title->FirstChild()->Value();
      CStdString strArtist;
      CStdString strAlbumName;

      if (artist && artist->FirstChild())
      {
        strArtist = artist->FirstChild()->Value();
        strAlbumName.Format("%s - %s",strArtist.c_str(),strTitle.c_str());
      }
      else
        strAlbumName = strTitle;

      if (year && year->FirstChild())
        strAlbumName.Format("%s (%s)",strAlbumName.c_str(),year->FirstChild()->Value());

      CScraperUrl url;
      if (!link)
        url.ParseString(scrURL.m_xml);

      while (link && link->FirstChild())
      {
        url.ParseElement(link);
        link = link->NextSiblingElement("url");
      }
      CMusicAlbumInfo newAlbum(strTitle, strArtist, strAlbumName, url);
      m_vecAlbums.push_back(newAlbum);
    }
    album = album->NextSiblingElement();
  }
  
  if (m_vecAlbums.size()>0)
    m_bSuccessfull=true;

  return;
}
示例#9
0
bool CGUIWindow::Load(TiXmlDocument &xmlDoc)
{
  TiXmlElement* pRootElement = xmlDoc.RootElement();
  if (strcmpi(pRootElement->Value(), "window"))
  {
    CLog::Log(LOGERROR, "file : XML file doesnt contain <window>");
    return false;
  }

  // set the scaling resolution so that any control creation or initialisation can
  // be done with respect to the correct aspect ratio
  g_graphicsContext.SetScalingResolution(m_coordsRes, m_needsScaling);

  // Resolve any includes that may be present
  g_SkinInfo->ResolveIncludes(pRootElement);
  // now load in the skin file
  SetDefaults();

  CGUIControlFactory::GetInfoColor(pRootElement, "backgroundcolor", m_clearBackground);
  CGUIControlFactory::GetMultipleString(pRootElement, "onload", m_loadActions);
  CGUIControlFactory::GetMultipleString(pRootElement, "onunload", m_unloadActions);
  CGUIControlFactory::GetHitRect(pRootElement, m_hitRect);

  TiXmlElement *pChild = pRootElement->FirstChildElement();
  while (pChild)
  {
    CStdString strValue = pChild->Value();
    if (strValue == "type" && pChild->FirstChild())
    {
      // if we have are a window type (ie not a dialog), and we have <type>dialog</type>
      // then make this window act like a dialog
      if (!IsDialog() && strcmpi(pChild->FirstChild()->Value(), "dialog") == 0)
        m_isDialog = true;
    }
    else if (strValue == "previouswindow" && pChild->FirstChild())
    {
      m_previousWindow = CButtonTranslator::TranslateWindow(pChild->FirstChild()->Value());
    }
    else if (strValue == "defaultcontrol" && pChild->FirstChild())
    {
      const char *always = pChild->Attribute("always");
      if (always && strcmpi(always, "true") == 0)
        m_defaultAlways = true;
      m_defaultControl = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "visible" && pChild->FirstChild())
    {
      CStdString condition;
      CGUIControlFactory::GetConditionalVisibility(pRootElement, condition);
      m_visibleCondition = g_infoManager.Register(condition, GetID());
    }
    else if (strValue == "animation" && pChild->FirstChild())
    {
      CRect rect(0, 0, (float)m_coordsRes.iWidth, (float)m_coordsRes.iHeight);
      CAnimation anim;
      anim.Create(pChild, rect, GetID());
      m_animations.push_back(anim);
    }
    else if (strValue == "zorder" && pChild->FirstChild())
    {
      m_renderOrder = atoi(pChild->FirstChild()->Value());
    }
    else if (strValue == "coordinates")
    {
      XMLUtils::GetFloat(pChild, "posx", m_posX);
      XMLUtils::GetFloat(pChild, "posy", m_posY);

      TiXmlElement *originElement = pChild->FirstChildElement("origin");
      while (originElement)
      {
        COrigin origin;
        originElement->QueryFloatAttribute("x", &origin.x);
        originElement->QueryFloatAttribute("y", &origin.y);
        if (originElement->FirstChild())
          origin.condition = g_infoManager.Register(originElement->FirstChild()->Value(), GetID());
        m_origins.push_back(origin);
        originElement = originElement->NextSiblingElement("origin");
      }
    }
    else if (strValue == "camera")
    { // z is fixed
      pChild->QueryFloatAttribute("x", &m_camera.x);
      pChild->QueryFloatAttribute("y", &m_camera.y);
      m_hasCamera = true;
    }
    else if (strValue == "controls")
    {
      TiXmlElement *pControl = pChild->FirstChildElement();
      while (pControl)
      {
        if (strcmpi(pControl->Value(), "control") == 0)
        {
          LoadControl(pControl, NULL);
        }
        pControl = pControl->NextSiblingElement();
      }
    }
    else if (strValue == "allowoverlay")
    {
      bool overlay = false;
      if (XMLUtils::GetBoolean(pRootElement, "allowoverlay", overlay))
        m_overlayState = overlay ? OVERLAY_STATE_SHOWN : OVERLAY_STATE_HIDDEN;
    }

    pChild = pChild->NextSiblingElement();
  }
  LoadAdditionalTags(pRootElement);

  m_windowLoaded = true;
  OnWindowLoaded();
  return true;
}
void CSettingsManager::write_SettingsXML()
{
  try
  {
    if(m_Settings.size() > 0)
    {
      TiXmlDocument doc;
      // ToDo: check all TiXml* generations!
      TiXmlDeclaration *declaration = new TiXmlDeclaration("1.0", "", "");
      doc.LinkEndChild(declaration);
      TiXmlComment *autoGenComment = new TiXmlComment();
      autoGenComment->SetValue(" THIS IS A AUTO GENERTATED FILE. DO NOT EDIT! ");
      doc.LinkEndChild(autoGenComment);

      for(SettingsMap::iterator mapIter = m_Settings.begin(); mapIter != m_Settings.end(); mapIter++)
      {
        vector<string> tokens;
        strTokenizer(mapIter->first, SETTINGS_SEPERATOR_STR, tokens);
        if(tokens.size() != 3)
        {
          doc.Clear();
          KODI->Log(LOG_ERROR, "Line: %i func: %s, Saving XML-File failed! Wrong SettingsMap string! Please call contact Addon author!\n", __LINE__, __func__, m_XMLFilename.c_str());
          return;
        }

        TiXmlElement *mainCategory = NULL;
        // check if this main category is already available
        for(TiXmlNode *element = doc.FirstChild(); element && !mainCategory; element = element->NextSiblingElement())
        {
          if(element->Value() == tokens[0])
          {
            mainCategory = static_cast<TiXmlElement*>(element);
          }
        }

        if(!mainCategory)
        { // create new main category
          mainCategory = new TiXmlElement(tokens[0]);
          doc.LinkEndChild(mainCategory);
        }

        TiXmlElement *settingsGroup = new TiXmlElement("settings_group");
        settingsGroup->SetAttribute("sub_category", tokens[1].c_str());
        settingsGroup->SetAttribute("group_name", tokens[2].c_str());
        mainCategory->LinkEndChild(settingsGroup);

        for(CSettingsList::iterator setIter=mapIter->second.begin(); setIter != mapIter->second.end(); setIter++)
        {
          if(!*setIter)
          {
            KODI->Log(LOG_ERROR, "Line: %i func: %s, invalid settings element! Please call contact Addon author!\n", __LINE__, __func__);
            return;
          }
          TiXmlElement *setting = new TiXmlElement("setting");
          setting->SetAttribute("key", (*setIter)->get_Key().c_str());

          switch((*setIter)->get_Type())
          {
            case ISettingsElement::STRING_SETTING:
              setting->SetAttribute("string", STRING_SETTINGS(*setIter)->get_Setting().c_str());
            break;

            case ISettingsElement::UNSIGNED_INT_SETTING:
              setting->SetAttribute("unsigned_int", toString(UNSIGNED_INT_SETTINGS(*setIter)->get_Setting()).c_str());
            break;

            case ISettingsElement::INT_SETTING:
              setting->SetAttribute("int", INT_SETTINGS(*setIter)->get_Setting());
            break;

            case ISettingsElement::FLOAT_SETTING:
              setting->SetDoubleAttribute("float", (double)FLOAT_SETTINGS(*setIter)->get_Setting());
            break;

            case ISettingsElement::DOUBLE_SETTING:
              setting->SetDoubleAttribute("double", DOUBLE_SETTINGS(*setIter)->get_Setting());
            break;

            case ISettingsElement::BOOL_SETTING:
              if(BOOL_SETTINGS(*setIter)->get_Setting())
              {
                setting->SetAttribute("bool", "true");
              }
              else
              {
                setting->SetAttribute("bool", "false");
              }
            break;

            default:
              KODI->Log(LOG_ERROR, "Line: %i func: %s, invalid settings type! Please call contact Addon author!\n", __LINE__, __func__);
              return;
            break;
          }

          settingsGroup->LinkEndChild(setting);
        }
      }

      if(!doc.SaveFile(m_XMLFilename.c_str()))
      {
        KODI->Log(LOG_ERROR, "Couldn't save XML settings to file %s", m_XMLFilename.c_str());
      }
    }
  }
  catch(bad_alloc &e)
  {
    KODI->Log(LOG_ERROR, "In function: %s a invalid memory allocation accured! Not enough free memory? Exception message: %s\n", __func__, e.what());
  }
}
示例#11
0
void Mapa::leerMapa(){

    //cargo la textura del fondo
    if(!fond.loadFromFile("resources/background.jpg")){
        std::cerr << "Error cargando la imagen background.png";
        exit(0);
    }
    fondo.setTexture(fond);

    //creo el objeto xml
    TiXmlDocument doc;
    doc.LoadFile("resources/mapaMario.tmx");
    TiXmlElement* map = doc.FirstChildElement("map");
    
    //leo sus atributos
    map->QueryIntAttribute("width",&_width);
    map->QueryIntAttribute("height",&_height);
    map->QueryIntAttribute("tilewidth",&_tileWidth);
    map->QueryIntAttribute("tileheight",&_tileHeigth);
    
    //Leemos las diferentes imagenes que nos sirven para hacer el rect de las texturas
    TiXmlElement *img = map->FirstChildElement("tileset");
    int numTil=0;
    while(img){
        numTil++;
        img=img->NextSiblingElement("tileset");
    }
    
    
    string filename;

    img = map->FirstChildElement("tileset");
    //guardamos en filename el spritesheet
    while(img){
        filename=(string)img->FirstChildElement("image")->Attribute("source");
        img=img->NextSiblingElement("tileset");
    }  
    
    //leemos las diferentes capas
    _tilesetTexture.loadFromFile(filename);
    TiXmlElement *layer = map->FirstChildElement("layer");
    while(layer){
        _numLayers++;
        layer= layer->NextSiblingElement("layer");
    }  
    
    //Reserva de memoria para saber el numnero de capas y el tamaño 
    _tilemap=new int**[_numLayers];
    for(int i=0; i<_numLayers; i++){
        _tilemap[i]=new int*[_height];
    }
    
    for(int l=0; l<_numLayers; l++){
        for(int y=0; y<_height; y++){
            _tilemap[l][y]=new int[_width];
        }
    }

    TiXmlElement *data;
    //leemos el atributo imagen
    layer = map->FirstChildElement("layer");
    string *name=new string[_numLayers];
    int j=0;
    int l=0;
    //leo los tiles del xml y avanzo a la siguiente posicion
    while(layer){
        data= layer->FirstChildElement("data")->FirstChildElement("tile");
        name[j]= (string)layer->Attribute("name");
            while(data){
                for(int y=0; y<_height; y++){
                    for(int x=0; x<_width;x++){
                        data->QueryIntAttribute("gid",&_tilemap[l][y][x]);
                        data=data->NextSiblingElement("tile");
                    }
                }
            }
        l++;
        layer= layer->NextSiblingElement("layer");
        j++;
    }
      
    //Reserva de memoria para los sprites
    _tilemapSprite=new sf::Sprite***[_numLayers];
      
    for(int l=0; l<_numLayers; l++){
        _tilemapSprite[l]=new sf::Sprite**[_height];
    }
      
    for(int l=0; l<_numLayers; l++){
        for(int y=0; y<_height; y++){
            _tilemapSprite[l][y]= new sf::Sprite*[_width];
            for(int x=0; x<_width; x++){
                _tilemapSprite[l][y][x]=new sf::Sprite();
            }
        }
    } 
    sf::Texture aux;  
    
    //falta el corte
    
    int columns = _tilesetTexture.getSize().x / _tileWidth;
    int rows = _tilesetTexture.getSize().y / _tileHeigth;
    
    cout<<columns<<" "<<rows<<endl; 
    
    _tilesetSprite =new sf::Sprite[columns*rows];     
    int t=0;
    for(int y=0; y<rows; y++){
        for(int x=0; x<columns;x++){
              _tilesetSprite[t].setTexture(_tilesetTexture);
              //_tilesetSprite[t].setTextureRect(sf::IntRect(left,top,width,height));//ojo si hay dos imagenes
              _tilesetSprite[t].setTextureRect(sf::IntRect(x*_tileWidth,y*_tileHeigth,_tileWidth,_tileHeigth));
              t++;
        }
    }
    
    cout<<"nostas"<<endl;
    /**
    for(int y=0; y<t; y++)
    {
     cout<<_tilesetSprite[y].getTextureRect().left<<" ";
     cout<<_tilesetSprite[y].getTextureRect().top<<" ";
      cout<<_tilesetSprite[y].getTextureRect().width<<" ";
       cout<<_tilesetSprite[y].getTextureRect().height<<endl;
    }**/
    
    //cout<<t<<endl;
   
    //asignacion sprite
      
    for(int l=0; l<_numLayers; l++){
        for(int y=0; y<_height; y++){
            for(int x=0; x<_width;x++){
                int gid=_tilemap[l][y][x]-1;
                if(gid>=rows*columns){
                    cout<<gid<<endl;
                    cout<<rows<<endl;
                    cout<<columns<<endl;
                    cout<<"Error aaaa"<<endl;
                }
                else if(gid>0){   

                    _tilemapSprite[l][y][x]=new sf::Sprite(_tilesetTexture,_tilesetSprite[gid].getTextureRect());
                    _tilemapSprite[l][y][x]->setPosition(x*_tileWidth,y*_tileHeigth);
                }
                else{
                    _tilemapSprite[l][y][x]=NULL;
                }
            }
        }
    }
      
    /////////////////////Resumen
    cout<<endl;
    cout<<"Resumen:"<<endl;
    cout<<"Heigth= "<<_height<<endl;
    cout<<"Width= "<<_width<<endl;
    cout<<"TileWidth= "<<_tileWidth<<endl;
    cout<<"TileHeigth= "<<_tileHeigth<<endl;
    cout<<"Numero de capas= "******"Nombre del tileset= "<<filename[0]<<endl;
    cout<<"Nombre del tileset= "<<filename[1]<<endl;
    cout<<endl;
     
     /**
    cout<<"Gid de las capas"<<endl;
   for(int l=0; l<_numLayers; l++)
    {
       cout<<name[l]<<endl;
        for(int y=0; y<_height; y++)
        {
            for(int x=0; x<_width;x++)
            {    
                cout<<_tilemap[l][y][x]<<" ";

                if(x==_width-1)
                {
                    cout<<endl;
                }
            }
        }
   }**/
}
void CSettingsManager::read_SettingsXML()
{
  TiXmlDocument xmlDoc;
  if(!xmlDoc.LoadFile(m_XMLFilename))
  {
    KODI->Log(LOG_NOTICE, "No initial settings XML file found.");
    return;
  }

  TiXmlElement *pRootElement = xmlDoc.RootElement();
  if(!pRootElement)
  {
    KODI->Log(LOG_NOTICE, "Settings XML file is empty.");
    return;
  }

  string mainCategory = pRootElement->Value();
  for(TiXmlNode *pGroupNode = pRootElement->FirstChild(); pGroupNode != NULL; pGroupNode = pRootElement->IterateChildren(pGroupNode))
  {
    if(pGroupNode->ValueStr() == "settings_group")
    {
      ATTRIBUTES_LIST groupAttributesList;
      if(pGroupNode && pGroupNode->Type() == TiXmlNode::TINYXML_ELEMENT)
      {
        getAttributesAsList(pGroupNode->ToElement(), groupAttributesList);
      }

      if(pGroupNode && pGroupNode->Type() == TiXmlNode::TINYXML_ELEMENT && groupAttributesList.size() == 2 && pGroupNode->ValueStr() == "settings_group")
      {
        string subCategory = "";
        string groupName = "";
        for(ATTRIBUTES_LIST::iterator iter = groupAttributesList.begin(); iter != groupAttributesList.end(); iter++)
        {
          if(iter->first == "sub_category")
          {
            subCategory = iter->second;
          }

          if(iter->first == "group_name")
          {
            groupName = iter->second;
          }
        }

        for(TiXmlNode *pKeyNode = pGroupNode->FirstChild(); pKeyNode != NULL; pKeyNode = pGroupNode->IterateChildren(pKeyNode))
        {
          if(pKeyNode && pKeyNode->Type() == TiXmlNode::TINYXML_ELEMENT && pKeyNode->ValueStr() == "setting")
          {
            ATTRIBUTES_LIST settingAttributesList;
            if(getAttributesAsList(pKeyNode->ToElement(), settingAttributesList) == 2)
            {
              string key = "";
              ISettingsElement::SettingsTypes type = ISettingsElement::UNKNOWN_SETTING;
              string value = "";
              for(ATTRIBUTES_LIST::iterator iter = settingAttributesList.begin(); iter != settingAttributesList.end(); iter++)
              {
                if(iter->first == "key")
                {
                  key = iter->second;
                }
                else
                {
                  type = CSettingsHelpers::TranslateTypeStrToEnum(iter->first);
                  value = iter->second;
                }
              }

              ISettingsElement *setting = find_Setting(mainCategory, subCategory, groupName, key);
              if(setting && setting->get_Type() == type)
              {
                switch(type)
                  {
                    case ISettingsElement::STRING_SETTING:
                      STRING_SETTINGS(setting)->set_Setting(value);
                    break;

                    case ISettingsElement::UNSIGNED_INT_SETTING:
                      {
                        unsigned int val = stringToVal<unsigned int>(value);
                        UNSIGNED_INT_SETTINGS(setting)->set_Setting(val);
                      }
                    break;

                    case ISettingsElement::INT_SETTING:
                      {
                        int val = stringToVal<int>(value);
                        INT_SETTINGS(setting)->set_Setting(val);
                      }
                    break;

                    case ISettingsElement::FLOAT_SETTING:
                      {
                        float val = stringToVal<float>(value);
                        FLOAT_SETTINGS(setting)->set_Setting(val);
                      }
                    break;

                    case ISettingsElement::DOUBLE_SETTING:
                      {
                        double val = stringToVal<double>(value);
                        DOUBLE_SETTINGS(setting)->set_Setting(val);
                      }
                    break;

                    case ISettingsElement::BOOL_SETTING:
                      if(value == "true" || value == "TRUE" || value == "True")
                      {
                        bool val = true;
                        BOOL_SETTINGS(setting)->set_Setting(val);
                      }
                      else if(value == "false" || value == "FALSE" || value == "False")
                      {
                        bool val = false;
                        BOOL_SETTINGS(setting)->set_Setting(val);
                      }
                      else
                      {
                        KODI->Log(LOG_ERROR, "CSettingsManager: Failed reading bool setting");
                      }
                    break;

                    default:
                      KODI->Log(LOG_ERROR, "CSettingsManager: Unknown settings type!");
                    break;
                  }
              }
              else
              {
                KODI->Log(LOG_ERROR, "CSettingsManager: Read settings element does not match the created settings element type!");
              }
            }
          }
        }
      }
    }
  }
}
示例#13
0
void TiXmlDocument::operator=( const TiXmlDocument& copy )
{
	Clear();
	copy.CopyTo( this );
}
示例#14
0
TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT )
{
	copy.CopyTo( this );
}
示例#15
0
bool WorkspaceLoader::Open(const wxString& filename, wxString& Title)
{
    TiXmlDocument doc;
    if (!TinyXML::LoadDocument(filename, &doc))
        return false;

//    ProjectManager* pMan = Manager::Get()->GetProjectManager();
//    LogManager* pMsg = Manager::Get()->GetLogManager();

    if (!GetpMan() || !GetpMsg())
        return false;

    // BUG: Race condition. to be fixed by Rick.
    // If I click close AFTER pMan and pMsg are calculated,
    // I get a segfault.
    // I modified classes projectmanager and logmanager,
    // so that when self==NULL, they do nothing
    // (constructors, destructors and static functions excempted from this)
    // This way, we'll use the *manager::Get() functions to check for nulls.

    TiXmlElement* root = doc.FirstChildElement("CodeBlocks_workspace_file");
    if (!root)
    {
        // old tag
        root = doc.FirstChildElement("Code::Blocks_workspace_file");
        if (!root)
        {
            GetpMsg()->DebugLog(_T("Not a valid Code::Blocks workspace file..."));
            return false;
        }
    }
    TiXmlElement* wksp = root->FirstChildElement("Workspace");
    if (!wksp)
    {
        GetpMsg()->DebugLog(_T("No 'Workspace' element in file..."));
        return false;
    }

    Title = cbC2U(wksp->Attribute("title")); // Conversion to unicode is automatic (see wxString::operator= )

    TiXmlElement* proj = wksp->FirstChildElement("Project");
    if (!proj)
    {
        GetpMsg()->DebugLog(_T("Workspace file contains no projects..."));
        return false;
    }

    // first loop to load projects
    while (proj)
    {
        if(Manager::isappShuttingDown() || !GetpMan() || !GetpMsg())
            return false;
        wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename")));
        if (projectFilename.IsEmpty())
        {
            GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?"));
        }
        else
        {
            wxFileName fname(projectFilename);
            wxFileName wfname(filename);
            fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
            int active = 0;
            int ret = proj->QueryIntAttribute("active", &active);
            switch (ret)
            {
                case TIXML_SUCCESS:
                    if (active == 1)
					{
						cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), true); // activate it
						if(!pProject)
						{
							cbMessageBox(_("Unable to open ") + projectFilename,
							 _("Opening WorkSpace") + filename, wxICON_WARNING);
						}
					}
                    break;
                case TIXML_WRONG_TYPE:
                    GetpMsg()->DebugLog(F(_T("Error %s: %s"), doc.Value(), doc.ErrorDesc()));
                    GetpMsg()->DebugLog(_T("Wrong attribute type (expected 'int')"));
                    break;
                default:
					cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), false); // don't activate it
					if(!pProject)
					{
						cbMessageBox(_("Unable to open ") + projectFilename,
						 _("Opening WorkSpace") + filename, wxICON_WARNING);
					}
                    break;
            }
        }
        proj = proj->NextSiblingElement("Project");
    }

    // second loop to setup dependencies
    proj = wksp->FirstChildElement("Project");
    while (proj)
    {
        cbProject* thisprj = 0;
        wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename")));
        if (projectFilename.IsEmpty())
        {
            GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?"));
            thisprj = 0;
        }
        else
        {
            wxFileName fname(projectFilename);
            wxFileName wfname(filename);
            fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
            thisprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath());
        }

        if (thisprj)
        {
            TiXmlElement* dep = proj->FirstChildElement("Depends");
            while (dep)
            {
                wxFileName fname(UnixFilename(cbC2U(dep->Attribute("filename"))));
                wxFileName wfname(filename);
                fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
                cbProject* depprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath());
                if (depprj)
                    Manager::Get()->GetProjectManager()->AddProjectDependency(thisprj, depprj);
                dep = dep->NextSiblingElement("Depends");
            }
        }
        proj = proj->NextSiblingElement("Project");
    }

    return true;
}
	bool OgreMeshLoader::LoadImpl( const STRING& filename, bool bFlipUV )
	{
		TiXmlDocument doc;
		if(!doc.LoadFile(filename.c_str()))
		{
			throw std::logic_error("Error, Can't load .mesh file! Please make sure it's xml format!");
			return false;
		}

		m_objs.clear();
		SR::RenderObject* obj = new SR::RenderObject;
		m_objs.push_back(obj);

		TiXmlElement* submeshNode = doc.FirstChildElement("mesh")->FirstChildElement("submeshes")->FirstChildElement("submesh");

		//读取面信息
		{
			TiXmlElement* facesNode = submeshNode->FirstChildElement("faces");
			int nFace = 0;
			facesNode->Attribute("count", &nFace);

			obj->m_faces.resize(nFace);

			int idx = 0;
			TiXmlElement* faceNode = facesNode->FirstChildElement("face");
			while (faceNode)
			{
				int v1, v2, v3;
				faceNode->Attribute("v1", &v1);
				faceNode->Attribute("v2", &v2);
				faceNode->Attribute("v3", &v3);

				SR::SFace face(v1, v2, v3);
				obj->m_faces[idx++] = std::move(face);

				faceNode = faceNode->NextSiblingElement("face");
			}
		}

		//读取顶点数据
		{
			TiXmlElement* geometryNode = submeshNode->FirstChildElement("geometry");
			int nVert = 0;
			geometryNode->Attribute("vertexcount", &nVert);

			obj->m_verts.resize(nVert);

			TiXmlElement* vbNode = geometryNode->FirstChildElement("vertexbuffer");
			//check what we have..
			if(vbNode->Attribute("positions") != STRING("true"))
			{
				throw std::logic_error("Error, the .mesh file doesn't even have vertex position info!");
				return false;
			}
			if(vbNode->Attribute("normals") != STRING("true"))
			{
				throw std::logic_error("Error, the .mesh file doesn't even have vertex normal info!");
				return false;
			}

			int idx = 0;
			TiXmlElement* vertNode = vbNode->FirstChildElement("vertex");
			while (vertNode)
			{
				//position
				TiXmlElement* posNode = vertNode->FirstChildElement("position");
				double x, y, z;
				posNode->Attribute("x", &x);
				posNode->Attribute("y", &y);
				posNode->Attribute("z", &z);

				//normal
				TiXmlElement* normalNode = vertNode->FirstChildElement("normal");
				double nx, ny, nz;
				normalNode->Attribute("x", &nx);
				normalNode->Attribute("y", &ny);
				normalNode->Attribute("z", &nz);

				//uv
				TiXmlElement* uvNode = vertNode->FirstChildElement("texcoord");
				double texu, texv;
				if(uvNode)
				{
					uvNode->Attribute("u", &texu);
					uvNode->Attribute("v", &texv);

					if(bFlipUV)
						texv = 1 - texv;
				}

				SR::SVertex vert;
				vert.pos = VEC4(x, y, z, 1);
				vert.normal = VEC3(nx, ny, nz);
				vert.normal.Normalize();
				if(uvNode)
					vert.uv = VEC2(texu, texv);
				obj->m_verts[idx++] = std::move(vert);

				vertNode = vertNode->NextSiblingElement("vertex");
			}
		}

		return true;
	}