bool cOpenALSoundEnvironment::CreateFromFile(const tString &asFile) { tString strType; TiXmlDocument doc; if (!doc.LoadFile(asFile.c_str())) return false; TiXmlElement* pMain = doc.FirstChildElement("SoundEnvironment")->FirstChildElement("Main"); if (pMain) { strType = pMain->Attribute("Type"); mstrName = pMain->Attribute("Name"); } float* pfTemp; TiXmlElement* pParams = doc.FirstChildElement("SoundEnvironment")->FirstChildElement("Parameters"); if ( (pParams == NULL) || (strType.compare("OpenAL")!=0) ) { doc.Clear(); return false; } mfDensity = cString::ToFloat(pParams->Attribute("Density"),0); mfDiffusion = cString::ToFloat(pParams->Attribute("Diffusion"),0); mfGain = cString::ToFloat(pParams->Attribute("Gain"),0); mfGainHF = cString::ToFloat(pParams->Attribute("GainHF"),0); mfGainLF = cString::ToFloat(pParams->Attribute("GainLF"),0); mfDecayTime = cString::ToFloat(pParams->Attribute("DecayTime"),0); mfDecayHFRatio = cString::ToFloat (pParams->Attribute("DecayHFRatio"),0); mfDecayLFRatio = cString::ToFloat (pParams->Attribute("DecayLFRatio"),0); mfReflectionsGain = cString::ToFloat(pParams->Attribute("ReflectionsGain"),0); mfReflectionsDelay = cString::ToFloat(pParams->Attribute("ReflectionsDelay"),0); pfTemp = cString::ToVector3f(pParams->Attribute("ReflectionsPan"),cVector3f(0)).v; mfReflectionsPan[0] = pfTemp[0]; mfReflectionsPan[1] = pfTemp[1]; mfReflectionsPan[2] = pfTemp[2]; mfLateReverbGain = cString::ToFloat(pParams->Attribute("LateReverbGain"),0); mfLateReverbDelay = cString::ToFloat(pParams->Attribute("LateReverbDelay"),0); pfTemp = cString::ToVector3f(pParams->Attribute("LateReverbPan"),cVector3f(0)).v; mfLateReverbPan[0] = pfTemp[0]; mfLateReverbPan[1] = pfTemp[1]; mfLateReverbPan[2] = pfTemp[2]; mfEchoTime = cString::ToFloat(pParams->Attribute("EchoTime"),0); mfEchoDepth = cString::ToFloat(pParams->Attribute("EchoDepth"),0); mfModulationTime = cString::ToFloat(pParams->Attribute("ModulationTime"),0); mfModulationDepth = cString::ToFloat(pParams->Attribute("ModulationDepth"),0); mfAirAbsorptionGainHF = cString::ToFloat(pParams->Attribute("AirAbsorptionGainHF"),0); mfHFReference = cString::ToFloat(pParams->Attribute("HFReference"),0); mfLFReference = cString::ToFloat(pParams->Attribute("LFReference"),0); mfRoomRolloffFactor =cString::ToFloat(pParams->Attribute("RoomRolloffFactor"),0); mbDecayHFLimit = cString::ToInt(pParams->Attribute("DecayHFLimit"),0); doc.Clear(); pParams = NULL; return true; }
void loadSetting(const char* fileName) { TiXmlDocument doc; if(!doc.LoadFile(fileName)) { LOG(ERROR) << doc.ErrorDesc(); return; } TiXmlElement* root = doc.FirstChildElement(); if(root == NULL) { LOG(ERROR) << "Failed to load file: No root element."; doc.Clear(); return; } uint16_t iCount = 0; for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { const char* tmp = elem->Attribute("Name"); if (strcmp(tmp,"lead") == 0) { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { iCount++; } break; } } if (iCount == 0) return; theApp.mElec = new Aelectrode[iCount]; theApp.elecNum = iCount; iCount = 0; for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { const char* tmp = elem->Attribute("Name"); if (strcmp(tmp, "lead") == 0) { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Attribute("ID") != NULL) theApp.mElec[iCount].eID = atoi(e->Attribute("ID")); if (e->Attribute("Name") != NULL) theApp.mElec[iCount].eName = e->Attribute("Name"); if (e->Attribute("point1") != NULL && e->Attribute("point2") != NULL) { theApp.mElec[iCount].ePos.x = atoi(e->Attribute("point1")); theApp.mElec[iCount].ePos.y = atoi(e->Attribute("point2")); } iCount++; } break; } } doc.Clear(); }
bool StoryDataCenter::LoadDataFromXML() { if (mIsLoadAllData) { return true; } mIsLoadAllData = true; std::string filePath = std::string("Data/") + std::string("cutscene.xml"); TiXmlElement *RootElement = initXML(filePath.c_str()); if (0 != RootElement) { TiXmlElement *childElement = RootElement->FirstChildElement(); while (0 != childElement) { ReadOneXmlItem(childElement); childElement = childElement->NextSiblingElement(); } TiXmlDocument *doc = RootElement->GetDocument(); doc->Clear(); CC_SAFE_DELETE(doc); GetMainLandStoryData(); } else { return false; } return true; }
void CreatureManager::loadCreatureBuffer(const std::string& buffer) { TiXmlDocument doc; doc.Parse(buffer.c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("cannot load creature buffer: %s", doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || (root->ValueStr() != "monster" && root->ValueStr() != "npc")) stdext::throw_exception("invalid root tag name"); std::string cName = root->Attribute("name"); stdext::tolower(cName); stdext::trim(cName); stdext::ucwords(cName); CreatureTypePtr newType(new CreatureType(cName)); for(TiXmlElement* attrib = root->FirstChildElement(); attrib; attrib = attrib->NextSiblingElement()) { if(attrib->ValueStr() != "look") continue; internalLoadCreatureBuffer(attrib, newType); break; } doc.Clear(); }
void CConnectRemoteMachineWindow::loadHistory() { CString appPath = GetAppPath(); CString fullPath = appPath + L"\\histroycommands1.xml"; char fname[4096] = {0}; int len = WideCharToMultiByte(CP_ACP, 0, fullPath, fullPath.GetLength(), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP,0, fullPath, fullPath.GetLength(), fname, len, NULL, NULL); fname[len + 1] = '\0'; TiXmlDocument *pDocument = new TiXmlDocument(fname); if(pDocument == NULL || !pDocument->LoadFile(TIXML_ENCODING_UTF8)) return; TiXmlElement *rootElement = pDocument->RootElement(); TiXmlNode* node = rootElement->FirstChild(); if(node) { do { std::string c = node->FirstChild()->Value(); wchar_t* strCommand = strutil::char2wchar(c.c_str()); m_historyCommand.push_back(strCommand); free(strCommand); }while((node = node->NextSibling())); } pDocument->Clear(); delete pDocument; }
//------------------------------------------------------------------------ bool StringParser::LoadStringItems( const string& fileList, const string& directory, bool isEncrypt ) { TiXmlDocument doc; if( !FileLoader::LoadFile( &doc, fileList, isEncrypt ) ) { Assert(0); _LogError( string("StringParser::LoadStringItems : ") + fileList + "¼ÓÔØʧ°Ü." ); return false; } TiXmlElement* root = doc.FirstChildElement( "StringList" ); if( root == 0 ) { doc.Clear(); Assert(0); _LogError( string("StringParser::LoadStringItems : ") + fileList + "¼ÓÔØʧ°Ü." ); return false; } TiXmlElement* entityNode = root->FirstChildElement( "StringFile" ); for( entityNode; entityNode; entityNode=entityNode->NextSiblingElement("StringFile") ) { const char* fileName = entityNode->Attribute( "File" ); LoadStringItem( directory + "\\" + fileName, isEncrypt ); } return true; }
void init_map_locs( const char *filename) { BMLoc loc; TiXmlDocument *xmlDoc = new TiXmlDocument( filename ); if (!xmlDoc->LoadFile() ) { printf("ERR! Can't load %s\n", filename ); } TiXmlElement *xLocationSet, *xLoc; TiXmlNode *xText; xLocationSet = xmlDoc->FirstChildElement( "locations" ); assert( xLocationSet ); xLoc = xLocationSet->FirstChildElement( "loc" ); int ndx = 0; while (xLoc) { loc.name = xLoc->Attribute("name"); const char *bg = xLoc->Attribute("bg"); if (!stricmp( bg, "forest")){ loc.bgType = BG_FOREST; } else if (!stricmp( bg, "ruins")) { loc.bgType = BG_RUINS; } else if (!stricmp( bg, "town")) { loc.bgType = BG_TOWN; } else { printf("WARNING: Unknown location background %s\n", bg ); loc.bgType = BG_FOREST; } xText = xLoc->FirstChild(); if (xText) { loc.desc = xText->Value(); } else { loc.desc = std::string("A mysterious (and violent) place.\n" ); } allLocs.push_back( loc ); xLoc = xLoc->NextSiblingElement( "loc" ); } xmlDoc->Clear(); delete xmlDoc; // Now initialize the icons mapIcons.push_back( load_bitmap( "gamedata/mapicon_forest.bmp", NULL ) ); mapIcons.push_back( load_bitmap( "gamedata/mapicon_ruins.bmp", NULL ) ); mapIcons.push_back( load_bitmap( "gamedata/mapicon_town.bmp", NULL ) ); bmpMtns = load_bitmap( "gamedata/map_mtns.bmp", NULL ); }
bool StringParser::LoadStringItem( const string& file, bool isEncrypt ) { TiXmlDocument doc; if( !FileLoader::LoadFile( &doc, file, isEncrypt ) ) { Assert(0); _LogError( string("StringParser::LoadStringItem : ") + file + "¼ÓÔØʧ°Ü." ); return false; } TiXmlElement* root = doc.FirstChildElement( "Strings" ); if( root == 0 ) { doc.Clear(); Assert(0); _LogError( string("StringParser::LoadStringItem : ") + file + "¼ÓÔØʧ°Ü." ); return false; } TiXmlElement* entityNode = root->FirstChildElement(); for( entityNode; entityNode; entityNode=entityNode->NextSiblingElement() ) { const char* key = entityNode->Value(); const char* text = entityNode->Attribute( "Text" ); if( text == 0 ) { _LogError( string("StringParser::LoadStringItem Error: ") + key + " ȱÉÙTextÊôÐÔ" ); continue; } if( m_StringItems.GetStringItemById( key ) != 0 ) { _LogError( string("StringParser::LoadStringItem Error: ") + key + " ÒÑ´æÔÚ" ); continue; } string theText = text; int len = ::strlen( text ); int start = 0; int replaceCount = 0; for( int i=0; i<len; ++i ) { /// Find "\n" if( text[i] == '\\' && i+1<len && text[i+1] == 'n' ) { theText.erase( theText.begin()+(i-replaceCount),theText.begin()+(i-replaceCount+2)); string strEnter = "\n"; theText.insert( theText.begin()+(i-replaceCount), strEnter.begin(), strEnter.begin()+strEnter.length() ); ++i; ++replaceCount; } } StringParser::StringItem* item = new StringParser::StringItem; Parse( key, We::Type::ToWstring( theText ), item ); m_StringItems.Add( item ); } return true; }
bool wxsItemResData::RebuildXrcFile() { // First - opening file TiXmlDocument Doc; TiXmlElement* Resources = nullptr; TiXmlElement* Object = nullptr; if ( TinyXML::LoadDocument(m_XrcFileName,&Doc) ) { Resources = Doc.FirstChildElement("resource"); } if ( !Resources ) { Doc.Clear(); Doc.InsertEndChild(TiXmlDeclaration("1.0","utf-8","")); Resources = Doc.InsertEndChild(TiXmlElement("resource"))->ToElement(); Resources->SetAttribute("xmlns","http://www.wxwidgets.org/wxxrc"); } // Searching for object representing this resource for ( Object = Resources->FirstChildElement("object"); Object; Object = Object->NextSiblingElement("object") ) { if ( cbC2U(Object->Attribute("name")) == m_ClassName ) { Object->Clear(); while ( Object->FirstAttribute() ) { Object->RemoveAttribute(Object->FirstAttribute()->Name()); } break; } } if ( !Object ) { Object = Resources->InsertEndChild(TiXmlElement("object"))->ToElement(); } // The only things left are: to dump item into object ... m_RootItem->XmlWrite(Object,true,false); Object->SetAttribute("name",cbU2C(m_ClassName)); for ( int i=0; i<GetToolsCount(); i++ ) { TiXmlElement* ToolElement = Object->InsertEndChild(TiXmlElement("object"))->ToElement(); m_Tools[i]->XmlWrite(ToolElement,true,false); } // ... and save back the file return TinyXML::SaveDocument(m_XrcFileName,&Doc); }
bool loadXMLFile (TiXmlDocument &pXMLDoc, std::string XMLFilename, std::map<int, std::string> * pMapXmlStrings, bool isSourceFile) { if (!pXMLDoc.LoadFile(XMLFilename.c_str())) { printf ("%s %s\n", pXMLDoc.ErrorDesc(), XMLFilename.c_str()); return false; } if (isSourceFile) GetEncoding(&pXMLDoc, sourceXMLEncoding); else GetEncoding(&pXMLDoc, foreignXMLEncoding); TiXmlElement* pRootElement = pXMLDoc.RootElement(); if (!pRootElement || pRootElement->NoChildren() || pRootElement->ValueTStr()!="strings") { printf ("error: No root element called: \"strings\" or no child found in input XML file: %s\n", XMLFilename.c_str()); return false; } if (isSourceFile) GetComment(pRootElement->FirstChild(), -1); const TiXmlElement *pChildElement = pRootElement->FirstChildElement("string"); const char* pAttrId = NULL; const char* pValue = NULL; std::string valueString; int id; while (pChildElement) { pAttrId=pChildElement->Attribute("id"); if (pAttrId && !pChildElement->NoChildren()) { id = atoi(pAttrId); if (pMapXmlStrings->find(id) == pMapXmlStrings->end()) { pValue = pChildElement->FirstChild()->Value(); valueString = EscapeLF(pValue); if (isSourceFile) multimapSourceXmlStrings.insert(std::pair<std::string,int>( valueString,id)); (*pMapXmlStrings)[id] = valueString; if (pChildElement && isSourceFile) GetComment(pChildElement->NextSibling(), id); } } pChildElement = pChildElement->NextSiblingElement("string"); } // Free up the allocated memory for the XML file pXMLDoc.Clear(); return true; }
void ThingTypeManager::loadXml(const std::string& file) { try { if(!isOtbLoaded()) stdext::throw_exception("OTB must be loaded before XML"); TiXmlDocument doc; doc.Parse(g_resources.readFileContents(file).c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("failed to parse '%s': '%s'", file, doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || root->ValueTStr() != "items") stdext::throw_exception("invalid root tag name"); for(TiXmlElement *element = root->FirstChildElement(); element; element = element->NextSiblingElement()) { if(unlikely(element->ValueTStr() != "item")) continue; uint16 id = element->readType<uint16>("id"); if(id != 0) { std::vector<std::string> s_ids = stdext::split(element->Attribute("id"), ";"); for(const std::string& s : s_ids) { std::vector<int32> ids = stdext::split<int32>(s, "-"); if(ids.size() > 1) { int32 i = ids[0]; while(i <= ids[1]) parseItemType(i++, element); } else parseItemType(atoi(s.c_str()), element); } } else { std::vector<int32> begin = stdext::split<int32>(element->Attribute("fromid"), ";"); std::vector<int32> end = stdext::split<int32>(element->Attribute("toid"), ";"); if(begin[0] && begin.size() == end.size()) { size_t size = begin.size(); for(size_t i = 0; i < size; ++i) while(begin[i] <= end[i]) parseItemType(begin[i]++, element); } } } doc.Clear(); m_xmlLoaded = true; g_logger.debug("items.xml read successfully."); } catch(std::exception& e) { g_logger.error(stdext::format("Failed to load '%s' (XML file): %s", file, e.what())); } }
int TextHandler::convert_word_to_text(const string & filepath, const TextID & tid, const string & file_type, string & text) { string cmd = "java -jar ./mdata/word/WordDocumentExtractor.jar parse -t \"" + file_type + "\" -i \"" + filepath + "\" -m \"" + m_word_workspace + "/" + tid + ".word.tmp\" -x \"" + m_word_workspace + "/" + tid + ".word.xml\""; system(cmd.c_str()); //读取原文件 string word_ext_result_file = m_word_workspace + "/" + tid + ".word.xml"; ByteBuffer data; if(false == read_file(word_ext_result_file, data) ) { return ERR_READ_WORD_EXT_FILE_FAILED; } //解析抽取出的XML stringstream ss; TiXmlDocument xmldoc; xmldoc.Parse(data.String().c_str()); TiXmlHandle docHandle( &xmldoc ); try { size_t idx = 0; TiXmlElement * elem = docHandle.FirstChild("document").Child("p", idx).ToElement(); while(elem) { const char * tmp = elem->GetText(); if(tmp) ss << tmp << endl; else ss << endl; ++idx; elem = docHandle.FirstChild("document").Child("p", idx).ToElement(); } }catch (...) { return ERR_PARSE_WORD_XML; } //清理XML资源 xmldoc.Clear(); text = ss.str(); return SUCCESS; }
void CStartServerWindow::loadLayouts() { CString appPath = GetAppPath(); CString fullPath = appPath + L"\\layouts.xml"; m_layoutlist.ResetContent(); layouts_.clear(); char fname[4096] = {0}; int len = WideCharToMultiByte(CP_ACP, 0, fullPath, fullPath.GetLength(), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP,0, fullPath, fullPath.GetLength(), fname, len, NULL, NULL); fname[len + 1] = '\0'; TiXmlDocument *pDocument = new TiXmlDocument(fname); if(pDocument == NULL || !pDocument->LoadFile(TIXML_ENCODING_UTF8)) return; TiXmlElement *rootElement = pDocument->RootElement(); TiXmlNode* node = rootElement->FirstChild(); if(node) { do { std::vector<LAYOUT_ITEM>& vec = layouts_[node->Value()]; wchar_t* ws = KBEngine::strutil::char2wchar(node->Value()); m_layoutlist.AddString(ws); free(ws); TiXmlNode* childnode = node->FirstChild(); if(childnode == NULL) break; do { LAYOUT_ITEM item; item.componentName = childnode->Value(); item.addr = childnode->FirstChild()->Value(); vec.push_back(item); }while((childnode = childnode->NextSibling())); }while((node = node->NextSibling())); } pDocument->Clear(); delete pDocument; }
void ParticleFactory::InitXML() { std::string pPath = GameResourceManager::sharedManager()->storedFullPathFromRelativePath("Data/particles.xml"); unsigned long _size; char *_pFileContent = (char*)CCFileUtils::sharedFileUtils()->getFileData(pPath.c_str() , "r", &_size); TiXmlDocument *_document = new TiXmlDocument(); _document->Parse(_pFileContent, 0, TIXML_ENCODING_UTF8); CC_SAFE_DELETE_ARRAY(_pFileContent); TiXmlElement *RootElement = _document->RootElement(); if (RootElement) { TiXmlElement *childElement = RootElement->FirstChildElement(); while (0 != childElement) { OneParticleInfo oneParticleInfo; TiXmlAttribute* pAttribute = childElement->FirstAttribute(); while(pAttribute) { std::string strName(pAttribute->Name()); std::string content = childElement->Attribute(strName.c_str()); if (strName == "ID") { unsigned int id = atoi(content.c_str()); oneParticleInfo.id = id; } else if (strName == "fileName") { oneParticleInfo.fileName = content; } pAttribute = pAttribute->Next(); } m_particleListInfo.insert(std::make_pair(oneParticleInfo.id,oneParticleInfo)); childElement = childElement->NextSiblingElement(); } TiXmlDocument *doc = RootElement->GetDocument(); doc->Clear(); CC_SAFE_DELETE(doc); } }
/** * 将键值对按照类似java中Properties类的xml格式存储 store "key-value" to xml file * @param filename 要保存的xml文件名 * @return 布尔值,代表操作执行成功与否 */ bool Properties::storeToXML(const string filename) const { TiXmlDocument doc; TiXmlDeclarationWithoutStandalone *decl = new TiXmlDeclarationWithoutStandalone("1.0", "UTF-8"); doc.LinkEndChild(decl); TiXmlDoctype *doctype = new TiXmlDoctype(); doctype->SetValue("properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\""); doc.LinkEndChild(doctype); TiXmlComment *comment1 = new TiXmlComment(); comment1->SetValue("This file is created by libproperties"); doc.LinkEndChild(comment1); TiXmlComment *comment2 = new TiXmlComment(); comment2->SetValue("read more from http://code.google.com/p/libproperties"); doc.LinkEndChild(comment2); TiXmlElement *propertiesElement = new TiXmlElement("properties"); doc.LinkEndChild(propertiesElement); for (const_iterator it = key_value.begin() ; it!=key_value.end() ; ++it ) { TiXmlElement *entryElement = new TiXmlElement("entry"); entryElement->LinkEndChild(new TiXmlText((*it).second)); #ifdef DEBUG_PROPERTIES_H propertiesElement->Print(stdout, 1); cout << endl; #endif propertiesElement->LinkEndChild(entryElement); entryElement->SetAttribute("key", (*it).first); } bool result = doc.SaveFile(filename); doc.Clear(); return result; }
void writeSetting(const char* fileName) { CString tempElecName[16] = {L"ml", L"cd1", L"cd2", L"tf1", L"f2", L"tf2", L"tf3", L"ld", L"ss", L"ss2", L"se3", L"af", L"af1", L"af2", L"af3", L"af4"}; TiXmlDocument doc; TiXmlElement* root = new TiXmlElement("root"); doc.LinkEndChild(root); TiXmlElement* element = new TiXmlElement("Lead"); element->SetAttribute("Name", "lead"); root->LinkEndChild(element); for (int i = 0; i < 16; i++) { TiXmlElement* element1 = new TiXmlElement((LPCSTR)(CStringA)itoS(i+1)); element->LinkEndChild(element1); element1->SetAttribute("Name", (LPCSTR)(CStringA)tempElecName[i]); } bool success = doc.SaveFile(fileName); doc.Clear(); }
void make_solution_for_ub( project_info_table& info ) { TiXmlDocument root; std::string path = util::string::wc2mb( info.project_file_path.c_str() ); root.LoadFile( path.c_str() ); std::string backup_path = path + "_backup"; root.SaveFile( backup_path.c_str() ); if ( root.Error() == true ) { printf( "loading error file : %s errorID : %d , errorRow : %d errorCol : %d" , path.c_str() , root.ErrorId() , root.ErrorRow() , root.ErrorCol() ); return; } TiXmlNode* pRoot = root.FirstChildElement("Project"); if ( pRoot == NULL ) return; TiXmlNode* pItemGroup = pRoot->FirstChild("ItemGroup"); if ( pItemGroup == NULL ) return; search_node( pItemGroup , info.filepath_table ); print_unity_x( info ); clear_unity_file( pRoot ); add_unity_file( pRoot ); root.SaveFile( path.c_str() ); root.Clear(); }
Object* ParticleSystemLoader::Load (const std::string& filename) { TiXmlDocument doc; if(!doc.LoadFile(filename.c_str ())) { return NULL; } TiXmlElement* root = doc.FirstChildElement ("ParticleSystem"); if (root == NULL) { return NULL; } ParticleSystem* partSys = new ParticleSystem (); TiXmlElement* content = root->FirstChildElement (); while (content) { std::string name = content->Value (); if (name == "CountRange") { ProcessPartCount (content, partSys); } else if (name == "EmissionRate") { ProcessEmissionRate (content, partSys); } else if (name == "Emiter") { ProcessEmiter (content, partSys, filename); } else if (name == "Renderer") { ProcessRenderer (content, partSys); } content = content->NextSiblingElement (); } doc.Clear (); return partSys; }
void CreatureManager::loadMonsters(const std::string& file) { TiXmlDocument doc; doc.Parse(g_resources.readFileContents(file).c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("cannot open monsters file '%s': '%s'", file, doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || root->ValueStr() != "monsters") stdext::throw_exception("malformed monsters xml file"); for(TiXmlElement* monster = root->FirstChildElement(); monster; monster = monster->NextSiblingElement()) { std::string fname = file.substr(0, file.find_last_of('/')) + '/' + monster->Attribute("file"); if(fname.substr(fname.length() - 4) != ".xml") fname += ".xml"; loadSingleCreature(fname); } doc.Clear(); m_loaded = true; }
void ThingTypeManager::loadXml(const std::string& file) { /// Read XML TiXmlDocument doc; doc.Parse(g_resources.loadFile(file).c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("failed to parse '%s': '%s'", file, doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || root->ValueTStr() != "items") stdext::throw_exception("invalid root tag name"); for (TiXmlElement *element = root->FirstChildElement(); element; element = element->NextSiblingElement()) { if(element->ValueTStr() != "item") continue; uint16 id = element->readType<uint16>("id"); if(id > 20000 && id < 20100) { id -= 20000; ItemTypePtr newType(new ItemType); newType->setServerId(id); addItemType(newType); } if(id != 0) parseItemType(id, element); else { uint16 fromId = element->readType<uint16>("fromid"), toId = element->readType<uint16>("toid"); for(uint16 i = fromId; i < toId; ++i) parseItemType(i, element); } } doc.Clear(); m_xmlLoaded = true; g_logger.debug("items.xml read successfully."); }
bool SData::LoadCache() { XBMC->Log(LOG_DEBUG, "%s", __FUNCTION__); std::string strCacheFile; TiXmlDocument doc; TiXmlElement *pRootElement = NULL; TiXmlElement *pTokenElement = NULL; strCacheFile = Utils::GetFilePath("cache.xml"); if (!doc.LoadFile(strCacheFile)) { XBMC->Log(LOG_ERROR, "%s: failed to load: \"%s\"", __FUNCTION__, strCacheFile.c_str()); return false; } pRootElement = doc.RootElement(); if (strcmp(pRootElement->Value(), "cache") != 0) { XBMC->Log(LOG_ERROR, "%s: invalid xml doc. root element 'cache' not found", __FUNCTION__); return false; } if (!m_bTokenManuallySet) { pTokenElement = pRootElement->FirstChildElement("token"); if (!pTokenElement || !pTokenElement->GetText()) { XBMC->Log(LOG_DEBUG, "%s: 'token' element not found", __FUNCTION__); } else { SC_STR_SET(m_identity.token, pTokenElement->GetText()); } XBMC->Log(LOG_DEBUG, "%s: token=%s", __FUNCTION__, m_identity.token); } doc.Clear(); return true; }
void CreatureManager::loadSpawns(const std::string& fileName) { if(!isLoaded()) { g_logger.warning("creatures aren't loaded yet to load spawns."); return; } if(m_spawnLoaded) { g_logger.warning("attempt to reload spawns."); return; } try { TiXmlDocument doc; doc.Parse(g_resources.readFileContents(fileName).c_str()); if(doc.Error()) stdext::throw_exception(stdext::format("cannot load spawns xml file '%s: '%s'", fileName, doc.ErrorDesc())); TiXmlElement* root = doc.FirstChildElement(); if(!root || root->ValueStr() != "spawns") stdext::throw_exception("malformed spawns file"); for(TiXmlElement* node = root->FirstChildElement(); node; node = node->NextSiblingElement()) { if(node->ValueTStr() != "spawn") stdext::throw_exception("invalid spawn node"); SpawnPtr spawn(new Spawn); spawn->load(node); m_spawns.insert(std::make_pair(spawn->getCenterPos(), spawn)); } doc.Clear(); m_spawnLoaded = true; } catch(std::exception& e) { g_logger.error(stdext::format("Failed to load '%s': %s", fileName, e.what())); } }
/** * Parses a Spriter SCML animations file using Tinyxml. * @param pNewSpriterAnimations TODO describtion. * @param pSCMLFileName TODO describtion. */ bool IND_SpriterManager::parseSpriterData(list<IND_SpriterEntity*> *pNewSpriterEntityList,const char *pSCMLFileName) { g_debug->header("Start parsing Spriter SGML file", 5); TiXmlDocument *eXmlDoc = new TiXmlDocument(pSCMLFileName); // Fatal error, cannot load if (!eXmlDoc->LoadFile()){ g_debug->header("Not able to load the Spriter SGML file", 2); return 0; } string spriterTopPath; string s = string(pSCMLFileName); unsigned int lastPosTemp = s.find_last_of("\\/"); if(lastPosTemp == string::npos){ spriterTopPath = "./"; } else{ spriterTopPath = s.substr(0, lastPosTemp + 1); } g_debug->header("Top directory : ", 3); g_debug->dataChar(spriterTopPath.c_str(), true); // Document root TiXmlElement *eSpriter_data = 0; eSpriter_data = eXmlDoc->FirstChildElement("spriter_data"); if (!eSpriter_data) { g_debug->header("Invalid name for Spriter document root, should be <spriter_data>", 2); eXmlDoc->Clear(); delete eXmlDoc; return 0; } // ----------------- Parse folders and create the images ----------------- TiXmlElement *eFolder = 0; eFolder = eSpriter_data->FirstChildElement("folder"); if (!eFolder) { g_debug->header("There are no Spriter resourcefolders to parse", 3); eXmlDoc->Clear(); delete eXmlDoc; return 0; } while (eFolder) { //printf("Folder: %s\n", eFolder->Attribute("name")); TiXmlElement *eFile = 0; eFile = eFolder->FirstChildElement("file"); while (eFile){ //printf(" id : %s\n", eFile->Attribute("id")); //printf(" name : %s\n", eFile->Attribute("name")); //printf(" width : %s\n", eFile->Attribute("width")); //printf(" height: %s\n", eFile->Attribute("height")); string result = spriterTopPath + string(eFile->Attribute("name")); IND_Image *mImageTemp = IND_Image::newImage(); if (!_imageManager->add(mImageTemp, result.c_str())){ g_debug->header("Unable to add Spriter image", 2); eXmlDoc->Clear(); delete eXmlDoc; return 0; } eFile = eFile->NextSiblingElement("file"); } eFolder = eFolder->NextSiblingElement("folder"); } // ----------------- Parse entities ----------------- TiXmlElement *eEntity = 0; eEntity = eSpriter_data->FirstChildElement("entity"); if (!eEntity) { g_debug->header("There are no entities to parse", 2); eXmlDoc->Clear(); delete eXmlDoc; return 0; } while (eEntity) { //IND_SpriterEntity *entityTemp = new IND_SpriterEntity(); TODO: use.... //printf("Entity id: %s\n", eEntity->Attribute("id")); TiXmlElement *eAnimation = 0; eAnimation = eEntity->FirstChildElement("animation"); while(eAnimation){ //printf(" id : %s\n", eAnimation->Attribute("id")); //printf(" name : %s\n", eAnimation->Attribute("name")); //printf(" length : %s\n", eAnimation->Attribute("length")); //printf(" looping: %s\n", eAnimation->Attribute("looping")); TiXmlElement *eMainline = 0; eMainline = eAnimation->FirstChildElement("mainline"); if (!eMainline) { g_debug->header("Animation is missing mainline", 2); eXmlDoc->Clear(); delete eXmlDoc; return 0; } TiXmlElement *eMKey = 0; eMKey = eMainline->FirstChildElement("key"); while (eMKey){ //printf(" id: %s", eMKey->Attribute("id")); //printf(" time: %s\n", eMKey->Attribute("time")); TiXmlElement *eObject_ref = 0; eObject_ref = eMKey->FirstChildElement("object_ref"); while (eObject_ref){ //printf(" id: %s", eObject_ref->Attribute("id")); //printf(" timeline: %s", eObject_ref->Attribute("timeline")); //printf(" key: %s", eObject_ref->Attribute("key")); //printf(" z_index: %s\n", eObject_ref->Attribute("z_index")); eObject_ref = eObject_ref->NextSiblingElement("object_ref"); } eMKey = eMKey->NextSiblingElement("key"); } TiXmlElement *eTimeline = 0; eTimeline = eAnimation->FirstChildElement("timeline"); while (eTimeline){ //printf("timeline id: %s\n", eTimeline->Attribute("id")); TiXmlElement *eTKey = 0; eTKey = eTimeline->FirstChildElement("key"); while (eTKey){ //printf(" id: %s", eTKey->Attribute("id")); //printf(" spin: %s\n", eTKey->Attribute("spin")); //TiXmlElement *eObject = 0; //eObject = eTKey->FirstChildElement("object"); // asumption: there is only one "object" element under the key.... //printf(" folder: %s", eObject->Attribute("folder")); //printf(" file: %s", eObject->Attribute("file")); //printf(" x: %s", eObject->Attribute("x")); //printf(" y: %s", eObject->Attribute("y")); //printf(" pivot_x: %s", eObject->Attribute("pivot_x")); //printf(" pivot_y: %s", eObject->Attribute("pivot_y")); //printf(" angle: %s\n", eObject->Attribute("angle")); eTKey = eTimeline->NextSiblingElement("key"); } eTimeline = eTimeline->NextSiblingElement("timeline"); } eAnimation = eAnimation->NextSiblingElement("animation"); } eEntity = eEntity->NextSiblingElement("entity"); } // Delete our allocated document and return success. eXmlDoc->Clear(); delete eXmlDoc; g_debug->header("End parsing Spriter SGML file", 6); return 1; }
void loadLanguage(const char* fileName) { TiXmlDocument doc; if(!doc.LoadFile(fileName)) { LOG(ERROR) << doc.ErrorDesc(); return; } TiXmlElement* root = doc.FirstChildElement(); if(root == NULL) { LOG(ERROR) << "Failed to load file: No root element."; doc.Clear(); return; } for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { if (elem->Value() == "File") { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == "File") theApp.mnLan->mnFile.strMenuName = e->Attribute("name"); if (e->Value() == "New") theApp.mnLan->mnFile.strNew = e->Attribute("name"); if (e->Value() == "Open") theApp.mnLan->mnFile.strOpen = e->Attribute("name"); if (e->Value() == "Close") theApp.mnLan->mnFile.strClose = e->Attribute("name"); if (e->Value() == "Save") theApp.mnLan->mnFile.strSave = e->Attribute("name"); if (e->Value() == "Print") theApp.mnLan->mnFile.strPrint = e->Attribute("name"); if (e->Value() == "Option") theApp.mnLan->mnFile.strOption = e->Attribute("name"); if (e->Value() == "PortName") theApp.mnLan->mnFile.strPortName = e->Attribute("name"); if (e->Value() == "BaudRate") theApp.mnLan->mnFile.strBaudRate = e->Attribute("name"); if (e->Value() == "PortScan") theApp.mnLan->mnFile.strScanPort = e->Attribute("name"); if (e->Value() == "PortOpen") theApp.mnLan->mnFile.strOpenPort = e->Attribute("name"); } } if (elem->Value() == "Option") { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == "Info") theApp.mnLan->mnOpt.strMenuName = e->Attribute("name"); if (e->Value() == "Info") theApp.mnLan->mnOpt.strInfo = e->Attribute("name"); if (e->Value() == "Analysis") theApp.mnLan->mnOpt.strAnl = e->Attribute("name"); if (e->Value() == "Montage") theApp.mnLan->mnOpt.strMon = e->Attribute("name"); if (e->Value() == "Event") theApp.mnLan->mnOpt.strEvent = e->Attribute("name"); if (e->Value() == "Log") theApp.mnLan->mnOpt.strLog = e->Attribute("name"); if (e->Value() == "WaveGen") theApp.mnLan->mnOpt.strWave = e->Attribute("name"); if (e->Value() == "Language") theApp.mnLan->mnOpt.strLan = e->Attribute("name"); } } if (elem->Value() == "Wave") { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == "Wave") theApp.mnLan->mnWave.strMenuName = e->Attribute("name"); if (e->Value() == "Start") theApp.mnLan->mnWave.strStart = e->Attribute("name"); if (e->Value() == "Stop") theApp.mnLan->mnWave.strStop = e->Attribute("name"); if (e->Value() == "Recording") theApp.mnLan->mnWave.strRecord = e->Attribute("name"); if (e->Value() == "Photic") theApp.mnLan->mnWave.strPhotic = e->Attribute("name"); if (e->Value() == "Sensitivity") theApp.mnLan->mnWave.strSensi = e->Attribute("name"); if (e->Value() == "PaperSpeed") theApp.mnLan->mnWave.strPaperSpeed = e->Attribute("name"); if (e->Value() == "LP") theApp.mnLan->mnWave.strLPF = e->Attribute("name"); if (e->Value() == "HP") theApp.mnLan->mnWave.strHPF = e->Attribute("name"); } } if (elem->Value() == "Help") { for(TiXmlElement* e = elem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == "Help") theApp.mnLan->mnHelp.strMenuName = e->Attribute("name"); if (e->Value() == "About") theApp.mnLan->mnHelp.strAbout = e->Attribute("name"); } } } doc.Clear(); };
TuringPtr generateTM(const std::string& fileName) { TiXmlDocument doc; std::string path = DATADIR + fileName; if(!doc.LoadFile(path.c_str())) { throw std::runtime_error("Error generating TM from XML: File not found!"); } TiXmlElement* root = doc.FirstChildElement(); std::string rootName; if(root == NULL) { throw std::runtime_error("Error generating TM from XML: Failed to load file: No root element."); doc.Clear(); } rootName = root->Value(); if (rootName != "TM") { throw std::runtime_error("Error generating TM from XML: Not a Turing Machine XML file!"); } std::set<char> alphabet; std::set<char> tapeAlphabet; bool allFound = false; char blank = 0; for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { //find alphabets and blank symbol std::string elemName = elem->Value(); if (elemName == "InputAlphabet") { for(TiXmlElement* elemOfSigma = elem->FirstChildElement(); elemOfSigma != NULL; elemOfSigma = elemOfSigma->NextSiblingElement()) { std::string elemOfSigmaName = elemOfSigma->Value(); if (elemOfSigmaName == "symbol") { TiXmlNode* e = elemOfSigma->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); if (t.size() != 1) throw std::runtime_error("Error generating TM from XML: One input symbol per node please"); alphabet.insert(t.front()); } } } if (elemName == "TapeAlphabet") { for(TiXmlElement* elemOfGamma = elem->FirstChildElement(); elemOfGamma != NULL; elemOfGamma = elemOfGamma->NextSiblingElement()) { std::string elemOfGammaName = elemOfGamma->Value(); if (elemOfGammaName == "symbol") { TiXmlNode* e = elemOfGamma->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); if (t.size() != 1) { throw std::runtime_error("Error generating TM from XML: One input symbol per node please"); } tapeAlphabet.insert(t.front()); } } } if (elemName == "Blank") { TiXmlNode* e = elem->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); if (t.size() != 1) { throw std::runtime_error("Error generating TM from XML: One blank symbol please"); } blank = t.front(); } if (tapeAlphabet.size() && alphabet.size() && blank) { //All arguments necessary to construct TM found allFound = true; break; } } if (!allFound) { throw std::runtime_error("Error generating TM from XML: Alphabet, tape alphabet or blank symbol missing!"); return nullptr; } TuringPtr TM(new TuringMachine(alphabet, tapeAlphabet, blank)); for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { //find alphabets and blank symbol std::string elemName = elem->Value(); if (elemName == "States") { const char* attr = elem->Attribute("storage"); bool hasStorage = false; std::vector<std::vector<char>> storages; if (attr) { std::string statesAttr(attr); if (statesAttr == "true") hasStorage = true; } if (hasStorage) { for(TiXmlElement* elemOfQ = elem->FirstChildElement(); elemOfQ != NULL; elemOfQ = elemOfQ->NextSiblingElement()) { std::string elemOfQName = elemOfQ->Value(); if (elemOfQName == "storage") { if (elemOfQ->FirstChild() == NULL) { storages.push_back(std::vector<char> ()); continue; } TiXmlNode* e = elemOfQ->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); std::vector<char> thisStorage; for (auto i : t) thisStorage.push_back(i); storages.push_back(thisStorage); } } } for(TiXmlElement* elemOfQ = elem->FirstChildElement(); elemOfQ != NULL; elemOfQ = elemOfQ->NextSiblingElement()) { bool isStarting = false; bool isAccepting = false; std::string elemOfQName = elemOfQ->Value(); if (elemOfQName == "state") { const char* attr = elemOfQ->Attribute("start"); if (attr) { std::string stateAttr(attr); if (stateAttr == "true") isStarting = true; } attr = elemOfQ->Attribute("accept"); if (attr) { std::string stateAttr(attr); if (stateAttr == "true") isAccepting = true; } if (elemOfQ->FirstChild() == NULL) { throw std::runtime_error("Error generating TM from XML: State without name"); } TiXmlNode* e = elemOfQ->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); if (!hasStorage) TM->addState(t, isStarting, isAccepting); else for (auto i : storages) TM->addState(t, isStarting, isAccepting, i); } } } if (elemName == "Transitions") { for(TiXmlElement* elemOfDelta = elem->FirstChildElement(); elemOfDelta != NULL; elemOfDelta = elemOfDelta->NextSiblingElement()) { std::string elemOfDeltaName = elemOfDelta->Value(); if (elemOfDeltaName == "transition") { std::string from = ""; std::string to = ""; std::vector<char> fromStorage; std::vector<char> toStorage; std::vector<char> read; std::vector<char> write; Direction dir = U; for(TiXmlElement* elemOfTransition = elemOfDelta->FirstChildElement(); elemOfTransition != NULL; elemOfTransition = elemOfTransition->NextSiblingElement()) { std::string elemOfTransitionName = elemOfTransition->Value(); if (elemOfTransitionName == "from") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); from = t; } if (elemOfTransitionName == "to") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); to = t; } if (elemOfTransitionName == "fromStorage") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) fromStorage.push_back(i); } if (elemOfTransitionName == "toStorage") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) toStorage.push_back(i); } if (elemOfTransitionName == "read") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) read.push_back(i); } if (elemOfTransitionName == "write") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) write.push_back(i); } if (elemOfTransitionName == "dir") { if (elemOfTransition->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfTransition->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); if (t == "L") dir = L; else if (t == "R") dir = R; else throw std::runtime_error("Error generating TM from XML: invalid direction" ); } } if (from.size() && to.size() && read.size() && write.size() && (dir == L || dir == R)) TM->addTransition(from, to, read, write, dir, fromStorage, toStorage); else throw std::runtime_error("Error generating TM from XML: Incomplete transition"); } } } } for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { //find alphabets and blank symbol std::string elemName = elem->Value(); if (elemName == "StartState") { std::string stateName = ""; std::vector<char> storage; for(TiXmlElement* elemOfSS = elem->FirstChildElement(); elemOfSS != NULL; elemOfSS = elemOfSS->NextSiblingElement()) { std::string elemOfSSName = elemOfSS->Value(); if (elemOfSSName == "name") { if (elemOfSS->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfSS->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; stateName = text->Value(); } if (elemOfSSName == "storage") { if (elemOfSS->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfSS->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) storage.push_back(i); } } if (stateName.size() != 0) { if (storage.size() == 0) TM->indicateStartState(stateName); else TM->indicateStartState(stateName, storage); } else throw std::runtime_error("Error generating TM from XML: No name for start state specified"); } if (elemName == "AcceptingStates") { for(TiXmlElement* elemOfAccepting = elem->FirstChildElement(); elemOfAccepting != NULL; elemOfAccepting = elemOfAccepting->NextSiblingElement()) { std::string elemOfAcceptingName = elemOfAccepting->Value(); if (elemOfAcceptingName == "state") { std::string stateName = ""; std::vector<char> storage; for(TiXmlElement* elemOfAccState = elemOfAccepting->FirstChildElement(); elemOfAccState != NULL; elemOfAccState = elemOfAccState->NextSiblingElement()) { std::string elemOfAccStateName = elemOfAccState->Value(); if (elemOfAccStateName == "name") { if (elemOfAccState->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfAccState->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; stateName = text->Value(); } if (elemOfAccStateName == "storage") { if (elemOfAccState->FirstChild() == NULL) { continue; } TiXmlNode* e = elemOfAccState->FirstChild(); TiXmlText* text = e->ToText(); if(text == NULL) continue; std::string t = text->Value(); for (auto i : t) storage.push_back(i); } } if (stateName.size() != 0) { if (storage.size() == 0) TM->indicateAcceptingState(stateName); else TM->indicateAcceptingState(stateName, storage); } else throw std::runtime_error("Error generating TM from XML: No name for accepting state specified"); } } } } return TM; }
/* ================== Parses and XML font file Uses Tinyxml ================== */ bool IND_FontManager::ParseFont (IND_Font *pNewFont, char *pFontName) { TiXmlDocument *mXmlDoc = new TiXmlDocument (pFontName); // Fatal error, cannot load if (!mXmlDoc->LoadFile()) return 0; // Document root TiXmlElement *mXFont = 0; mXFont = mXmlDoc->FirstChildElement("font"); if (!mXFont) { Debug->Header ("Invalid name for document root, should be <font>", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } if (mXFont->Attribute("num_characters")) { pNewFont->mFont.mNumChars = atoi (mXFont->Attribute("num_characters")); pNewFont->SetLetters (new IND_Font::LETTER [pNewFont->GetNumChars()]); } else { Debug->Header ("The font doesn't have a \"num_characters\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } TiXmlElement *mXChar= 0; mXChar = mXFont->FirstChildElement("char"); if (!mXChar) { Debug->Header ("There are no chars to parse", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Parse all the chars int mCont = 0; while (mXChar) { // Id if (mXChar->Attribute("id")) { pNewFont->GetLetters() [mCont].mLetter = atoi (mXChar->Attribute("id")); } else { Debug->Header ("The char doesn't have a \"id\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // x if (mXChar->Attribute("x")) { pNewFont->GetLetters() [mCont].mOffsetX = atoi (mXChar->Attribute("x")); } else { Debug->Header ("The char doesn't have a \"x\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // y if (mXChar->Attribute("y")) { pNewFont->GetLetters() [mCont].mOffsetY = atoi (mXChar->Attribute("y")); } else { Debug->Header ("The char doesn't have a \"y\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // width if (mXChar->Attribute("width")) { pNewFont->GetLetters() [mCont].mWidthChar = atoi (mXChar->Attribute("width")); } else { Debug->Header ("The char doesn't have a \"width\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // height if (mXChar->Attribute("height")) { pNewFont->GetLetters() [mCont].mHeightChar = atoi (mXChar->Attribute("height")); } else { Debug->Header ("The char doesn't have a \"height\" attribute", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next char declaration mXChar = mXChar->NextSiblingElement("char"); mCont++; } mXmlDoc->Clear(); delete mXmlDoc; return 1; }
/* ================== Parses an MudFont XML font file Uses Tinyxml ================== */ bool IND_FontManager::parseMudFont(IND_Font *pNewFont,const char *pFontName) { TiXmlDocument *mXmlDoc = new TiXmlDocument(pFontName); // Fatal error, cannot load if (!mXmlDoc->LoadFile()) { DISPOSE(mXmlDoc); return 0; } // Setting the type of the font pNewFont->setFontType(IND_Font::FONTTYPE_MudFont); // Document root TiXmlElement *mXFont = 0; mXFont = mXmlDoc->FirstChildElement("font"); if (!mXFont) { g_debug->header("Invalid name for document root, should be <font>", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } if (mXFont->Attribute("num_characters")) { pNewFont->setNumChars(atoi(mXFont->Attribute("num_characters"))); pNewFont->setLetters(new IND_Font::LETTER [pNewFont->getNumChars()]); } else { g_debug->header("The font doesn't have a \"num_characters\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } TiXmlElement *mXChar = 0; mXChar = mXFont->FirstChildElement("char"); if (!mXChar) { g_debug->header("There are no chars to parse", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Parse all the chars int mCont = 0; while (mXChar) { // Id if (mXChar->Attribute("id")) { pNewFont->getLetters() [mCont]._letter = static_cast<unsigned char>(atoi(mXChar->Attribute("id"))); } else { g_debug->header("The char doesn't have a \"id\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // x if (mXChar->Attribute("x")) { pNewFont->getLetters() [mCont]._x = atoi(mXChar->Attribute("x")); } else { g_debug->header("The char doesn't have a \"x\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // y if (mXChar->Attribute("y")) { pNewFont->getLetters() [mCont]._y = atoi(mXChar->Attribute("y")); } else { g_debug->header("The char doesn't have a \"y\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // width if (mXChar->Attribute("width")) { pNewFont->getLetters() [mCont]._width = atoi(mXChar->Attribute("width")); } else { g_debug->header("The char doesn't have a \"width\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // height if (mXChar->Attribute("height")) { pNewFont->getLetters() [mCont]._height = atoi(mXChar->Attribute("height")); } else { g_debug->header("The char doesn't have a \"height\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next char declaration mXChar = mXChar->NextSiblingElement("char"); mCont++; } mXmlDoc->Clear(); delete mXmlDoc; return 1; }
/* ================== Parses an Angelcode XML font file Uses Tinyxml ================== */ bool IND_FontManager::parseAngelCodeFont(IND_Font *pNewFont,const char *pFileName, IND_Type pType, IND_Quality pQuality) { TiXmlDocument *mXmlDoc = new TiXmlDocument(pFileName); // Fatal error, cannot load if (!mXmlDoc->LoadFile()) { DISPOSE(mXmlDoc); return 0; } // Setting font filename pNewFont->setFileName(pFileName); // Setting the type of the font pNewFont->setFontType(IND_Font::FONTTYPE_AngelCode); // Document root TiXmlElement *mXFont = 0; mXFont = mXmlDoc->FirstChildElement("font"); if (!mXFont) { g_debug->header("Invalid name for document root, should be <font>", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } //TODO : info element variables ... maybe //TODO : common element variables ... maybe //TODO : pages, this one needs to be done ... MudFont have (allways?) just one page .. Angelcode can have multiple // Image loading // Pages element TiXmlElement *mXPages = 0; mXPages = mXFont->FirstChildElement("pages"); if (!mXPages) { g_debug->header("The <font> element doesn't have a <pages> child element", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Page element TiXmlElement *mXPage = 0; mXPage = mXPages->FirstChildElement("page"); if (!mXPage) { g_debug->header("There are no <page> elements to parse", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Parse each page int mPageCount = 0; while (mXPage) { // Id if (mXPage->Attribute("id")) { //pNewFont->getLetters() [mCharCount]._letter = static_cast<unsigned char>(atoi(mXChar->Attribute("id"))); //TODO : FIXME !! id refers to font image, starting from 0 -> } else { g_debug->header("The <page> element doesn't have a \"id\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // File if (mXPage->Attribute("file")) { IND_Image *mNewImage = IND_Image::newImage(); bool noImgError = _imageManager->add(mNewImage, mXPage->Attribute("file")); if (!noImgError) { DISPOSEMANAGED(mNewImage); g_debug->header("Failed at adding page image for Angelcode font", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // ----- Width and height of the bitmap font MUST be power of two ----- IND_Math mMath; if (!mMath.isPowerOfTwo(mNewImage->getWidth()) || !mMath.isPowerOfTwo(mNewImage->getHeight())) { g_debug->header("This operation can not be done", DebugApi::LogHeaderInfo); g_debug->dataChar("", 1); g_debug->header("The height and width of the AngelCode font font must be power of 2", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // ----- Bitmap (IND_Surface object) creation ----- IND_Surface *mNewSurface = IND_Surface::newSurface(); if (!_surfaceManager->add(mNewSurface, mNewImage, pType, pQuality)) { mXmlDoc->Clear(); delete mXmlDoc; return 0; } // IND_Surface object MUST have one block ONLY if (mNewSurface->getNumBlocks() > 1) { mXmlDoc->Clear(); delete mXmlDoc; _surfaceManager->remove(mNewSurface); return 0; } pNewFont->setSurface(mNewSurface); // TODO: somehow handle more than one font surface, - this relates to the "id" attribute parsed.. } else { g_debug->header("The <page> element doesn't have a \"file\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next char declaration mXPage = mXPage->NextSiblingElement("page"); mPageCount++; } // Chars element TiXmlElement *mXChars = 0; mXChars = mXFont->FirstChildElement("chars"); if (!mXChars) { g_debug->header("The <font> element doesn't have a <chars> child element", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } if (mXChars->Attribute("count")) { pNewFont->setNumChars(atoi(mXChars->Attribute("count"))); pNewFont->setLetters(new IND_Font::LETTER [pNewFont->getNumChars()]); } else { g_debug->header("The <chars> element doesn't have a \"count\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Char element TiXmlElement *mXChar = 0; mXChar = mXChars->FirstChildElement("char"); if (!mXChar) { g_debug->header("There are no <char> elements to parse", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Parse each char int mCharCount = 0; while (mXChar) { // Id if (mXChar->Attribute("id")) { pNewFont->getLetters() [mCharCount]._letter = static_cast<unsigned char>(atoi(mXChar->Attribute("id"))); } else { g_debug->header("The <char> element doesn't have a \"id\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // x if (mXChar->Attribute("x")) { pNewFont->getLetters() [mCharCount]._x = atoi(mXChar->Attribute("x")); } else { g_debug->header("The <char> element doesn't have a \"x\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // y if (mXChar->Attribute("y")) { pNewFont->getLetters() [mCharCount]._y = atoi(mXChar->Attribute("y")); } else { g_debug->header("The <char> element doesn't have a \"y\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // width if (mXChar->Attribute("width")) { pNewFont->getLetters() [mCharCount]._width = atoi(mXChar->Attribute("width")); } else { g_debug->header("The <char> element doesn't have a \"width\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // height if (mXChar->Attribute("height")) { pNewFont->getLetters() [mCharCount]._height = atoi(mXChar->Attribute("height")); } else { g_debug->header("The <char> element doesn't have a \"height\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // xoffset if (mXChar->Attribute("xoffset")) { pNewFont->getLetters() [mCharCount]._xOffset = atoi(mXChar->Attribute("xoffset")); } else { g_debug->header("The char doesn't have a \"xoffset\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // yoffset if (mXChar->Attribute("yoffset")) { pNewFont->getLetters() [mCharCount]._yOffset = atoi(mXChar->Attribute("yoffset")); } else { g_debug->header("The <char> element doesn't have a \"yoffset\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // xadvance if (mXChar->Attribute("xadvance")) { pNewFont->getLetters() [mCharCount]._xAdvance = atoi(mXChar->Attribute("xadvance")); } else { g_debug->header("The <char> element doesn't have a \"xadvance\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // page if (mXChar->Attribute("page")) { pNewFont->getLetters() [mCharCount]._page = atoi(mXChar->Attribute("page")); } else { g_debug->header("The <char> element doesn't have a \"page\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // chnl if (mXChar->Attribute("chnl")) { pNewFont->getLetters() [mCharCount]._chnl = atoi(mXChar->Attribute("chnl")); } else { g_debug->header("The <char> element doesn't have a \"chnl\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next char declaration mXChar = mXChar->NextSiblingElement("char"); mCharCount++; } // Kernings element TiXmlElement *mXKernings = 0; mXKernings = mXFont->FirstChildElement("kernings"); if (!mXKernings) { g_debug->header("The <font> element doesn't have a <kernings> child element", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } if (mXKernings->Attribute("count")) { pNewFont->setNumKernings(atoi(mXKernings->Attribute("count"))); pNewFont->setKernings(new IND_Font::KERNING [pNewFont->getNumKernings()]); } else { g_debug->header("The <kernings> element doesn't have a \"count\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Kerning element TiXmlElement *mXKerning = 0; mXKerning = mXKernings->FirstChildElement("kerning"); if (!mXKerning) { g_debug->header("There are no <kerning> elements to parse", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Parse each kerning int mKerCount = 0; while (mXKerning) { // First if (mXKerning->Attribute("first")) { pNewFont->getKernings()[mKerCount]._first = atoi(mXKerning->Attribute("first")); } else { g_debug->header("The <kerning> element doesn't have a \"first\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Second if (mXKerning->Attribute("second")) { pNewFont->getKernings()[mKerCount]._second = atoi(mXKerning->Attribute("second")); } else { g_debug->header("The <kerning> element doesn't have a \"second\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Amount if (mXKerning->Attribute("amount")) { pNewFont->getKernings()[mKerCount]._amount = atoi(mXKerning->Attribute("amount")); } else { g_debug->header("The <kerning> element doesn't have a \"second\" attribute", DebugApi::LogHeaderError); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next kerning declaration mXKerning = mXKerning->NextSiblingElement("kerning"); mKerCount++; } mXmlDoc->Clear(); delete mXmlDoc; return 1; }
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 & 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 = '>' />" ); 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 "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright ©.\"> </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 "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, 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
</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></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 & 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 & away ", c1->Value(), true ); } #endif { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & 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 & 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; }
void WaypointManager::LoadWaypoints(SDL_Renderer* renderer) { //Get the whole xml document. TiXmlDocument doc; if(!doc.LoadFile(kTilemapPath)) { cerr << doc.ErrorDesc() << endl; } //Now get the root element. TiXmlElement* root = doc.FirstChildElement(); if(!root) { cerr << "Failed to load file: No root element." << endl; doc.Clear(); } else { float x = 0; float y = 0; int id = -1; vector<int> connections; //Jump to the first 'objectgroup' element. for(TiXmlElement* groupElement = root->FirstChildElement("objectgroup"); groupElement != NULL; groupElement = groupElement->NextSiblingElement()) { string name = groupElement->Attribute("name"); if(name == "WaypointLayer") { //Jump to the first 'object' element - within 'objectgroup' for(TiXmlElement* objectElement = groupElement->FirstChildElement("object"); objectElement != NULL; objectElement = objectElement->NextSiblingElement()) { string name = objectElement->Attribute("name"); if(name == "Waypoint") { x = (float)atof(objectElement->Attribute("x")); y = (float)atof(objectElement->Attribute("y")); //Jump to the first 'properties' element - within 'object' for(TiXmlElement* propertiesElement = objectElement->FirstChildElement("properties"); propertiesElement != NULL; propertiesElement = propertiesElement->NextSiblingElement()) { //Loop through the 'property' elements - within 'properties' for(TiXmlElement* propertyElement = propertiesElement->FirstChildElement("property"); propertyElement != NULL; propertyElement = propertyElement->NextSiblingElement()) { string name = propertyElement->Attribute("name"); if(name == "Connections") { //Split up the comma delimited connections. stringstream ss(propertyElement->Attribute("value")); int i; while(ss >> i) { connections.push_back(i); if(ss.peek() == ',') ss.ignore(); } } else if(name == "ID") { id = atoi(propertyElement->Attribute("value")); } } //Add the new waypoint with the read in details. mWaypoints.push_back(new Waypoint(renderer, id, Vector2D(x,y), connections)); connections.clear(); } } } }