void Config::LoadConfigIO() { std::string file = Utils::getConfigFile(IO_CONFIG); if (!Utils::fileExists(file)) { std::ofstream conf(file.c_str(), std::ofstream::out); conf << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" << std::endl; conf << "<calaos:ioconfig xmlns:calaos=\"http://www.calaos.fr\">" << std::endl; conf << "<calaos:home></calaos:home>" << std::endl; conf << "</calaos:ioconfig>" << std::endl; conf.close(); } TiXmlDocument document(file); if (!document.LoadFile()) { cError() << "There was a parse error"; cError() << document.ErrorDesc(); cError() << "In file " << file << " At line " << document.ErrorRow(); exit(-1); } TiXmlHandle docHandle(&document); TiXmlElement *room_node = docHandle.FirstChildElement("calaos:ioconfig").FirstChildElement("calaos:home").FirstChildElement().ToElement(); for(; room_node; room_node = room_node->NextSiblingElement()) { if (room_node->ValueStr() == "calaos:room" && room_node->Attribute("name") && room_node->Attribute("type")) { std::string name, type; int hits = 0; name = room_node->Attribute("name"); type = room_node->Attribute("type"); if (room_node->Attribute("hits")) room_node->Attribute("hits", &hits); Room *room = new Room(name, type, hits); ListeRoom::Instance().Add(room); room->LoadFromXml(room_node); } } cInfo() << "Done. "; }
/** Wczytuje atrybuty algorytmu. Wczytana zostaje miedzy innymi nazwa alogrytmu. @param algo Wskaznik do konfigurowanego algorytmu */ void XMLConfigFile::LoadAlgorithmSettings(Algorithm* algo) { TRACE( "XMLConfigFile::LoadAlgorithmSettings - Wczytywanie ustawien algorytmu...\n" ); TiXmlElement* algoXmlElem; TiXmlNode* algoXmlNode; string algoName; TiXmlHandle docHandle( &document ); algoXmlNode = docHandle.FirstChild( "algorithm" ).Node(); if(algoXmlElem != NULL) { algoXmlElem = algoXmlNode->ToElement(); if( algoXmlElem->Attribute("name") ) algo->SetName( algoXmlElem->Attribute("name") ); } }
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; }
/** Returns the player list from the xml file * * This function is used by the AccountList class to get the * playerlist. This list is then iterates and we can feed the list of * player names. * * \return A list of player */ RainbruRPG::Gui::tAccountList* RainbruRPG::Network::Ident:: xmlAccountList::getAccountList(){ tAccountList* pl= new tAccountList(); if (doc){ TiXmlHandle docHandle( doc ); TiXmlElement* child = docHandle.FirstChild( "PlayerList" ) .FirstChild( "Player" ).Element(); for( child; child; child=child->NextSiblingElement() ){ tAccountListItem *it=new tAccountListItem(); it->name= getXMLTextFromName(child, "Name"); it->password= getXMLTextFromName(child, "Pwd"); it->mail= getXMLTextFromName(child, "Mail"); it->validationId= getXMLTextFromName(child, "ConfirmId"); // Get the creation timestamp xmlTimestamp xts; it->creation= xts.getCTimeS("creation", child); // Get the confirmation timestamp it->confirm= xts.getCTimeS("confirm", child); LOGCATS("Account : name='"); LOGCATS(it->name); LOGCATS("' confirm='"); LOGCATS(it->confirm.c_str()); LOGCATS("'"); LOGCAT(); const char* bl=getXMLTextFromName(child, "Black"); if (strcmp( bl, "Yes")==0) it->blacklist=true; else it->blacklist=false; pl->push_back(it); } return pl; } else{ LOGW(_("Cannot get a valid root element, account list will be NULL")); return NULL; } }
/** * @method CGame::init() * @desc inititalizes the Game managers like input manager, sound manager etc. */ void CGame::init() { doc = new TiXmlDocument("content/angrybirds.xml"); levelNumber = 0; bool loadOkay = doc->LoadFile(); assert(loadOkay); TiXmlHandle docHandle(doc); CGame::destroyed = false; CGame::mGameState = START_MENU; birdCount = 0; InputManagerC::CreateInstance()->init(); PhysicsWorld::getInstance()->init(docHandle.FirstChildElement().ChildElement("physics", 0).Element()); Background::createInstance()->init(docHandle.FirstChildElement().ChildElement("backgrounds", 0).ChildElement("mainmenu", 0).Element()->Attribute("src")); strcpy_s(levelBackgroundSrc, docHandle.FirstChildElement().ChildElement("backgrounds", 0).ChildElement("level", 0).Element()->Attribute("src")); score = new Score(); score->init(docHandle.FirstChildElement().ChildElement("score", 0).Element(), birdCount); winScreen = new WinScreen(); winScreen->init("content/Textures/WinScreen.png"); loseScreen = new LoseScreen(); loseScreen->init("content/Textures/LoseScreen.png"); playButton = new Button(); playButton->init(docHandle.FirstChildElement().ChildElement("playbutton", 0).Element()); nextButton = new Button(); nextButton->init(docHandle.FirstChildElement().ChildElement("nextbutton", 0).Element()); previousButton = new Button(); previousButton->init(docHandle.FirstChildElement().ChildElement("previousbutton", 0).Element()); resetButton = new Button(); resetButton->init(docHandle.FirstChildElement().ChildElement("resetbutton", 0).Element()); AngryBirdsMouse::getInstance()->init(docHandle.FirstChildElement().ChildElement("mouse", 0).Element()); SoundManagerC::CreateInstance()->init(); }
/** * @method CGame::loadNextLevel() * @desc calls the loadLevel functions of the player, block and pig manager and passses the new level xml to them */ void CGame::loadNextLevel() { TiXmlHandle docHandle(doc); SoundManagerC::GetInstance()->PauseBG(false); if (docHandle.FirstChildElement().ChildElement("level", levelNumber).ChildElement("birds", 0).Element() != NULL) { PlayerManager::getInstance()->loadLevel(docHandle.FirstChildElement().ChildElement("level", levelNumber).ChildElement("birds", 0).Element()); BlockManager::getInstance()->loadLevel(docHandle.FirstChildElement().ChildElement("level", levelNumber).ChildElement("blocks", 0).Element()); PigManager::getInstance()->loadLevel(docHandle.FirstChildElement().ChildElement("level", levelNumber).ChildElement("pigs", 0).Element()); gameOver = false; } else { levelNumber--; } }
/*! * \fn Parser::dbCheck() * \brief Check the database file. * \return true if database is ok, false otherwise. */ bool Parser::dbCheck() { std::cout << "(func) Parser::CheckDb" << std::endl; // dbPath strncpy(dbPath, "databases/", 512); strncat(dbPath, dbLng , 4); strncat(dbPath, "/xxx.xml", 512); //std::cout << " path : " << dbPath << std::endl; tinyxml2::XMLDocument dbFile; if (dbFile.LoadFile(dbPath) != tinyxml2::XML_NO_ERROR) { std::cerr << "[error] Unable to open database! ERROR #" << dbFile.ErrorID() << std::endl; return false; } else { tinyxml2::XMLHandle docHandle(&dbFile); infos = docHandle.FirstChildElement("database").FirstChildElement("infos").ToElement(); if (!infos) { dbStat = false; return false; } else { double dbVersion = 0.0; infos->QueryDoubleAttribute("version", &dbVersion); if (dbVersion != 1.0) { dbStat = false; return false; } else { dbStat = true; std::cout << " database successfully opened !" << std::endl; return true; } } } return false; }
TiXmlElement const * Setting::get(std::string const & path) const { if (!loaded_) { load_(); } TiXmlHandle docHandle(&configFile_); std::string partPath = ""; for (size_t i = 0; i < path.size(); ++i) { if (path[i] != '.') { partPath.push_back(path[i]); continue; } docHandle = docHandle.FirstChild(partPath.c_str()); partPath = ""; } return docHandle.FirstChild(partPath.c_str()).ToElement(); }
bool cAlarmServer::loadAlarmDefinitions(const UtlString& alarmFile) { OsSysLog::add(FAC_ALARM, PRI_DEBUG, "Loading alarm def file '%s'", alarmFile.data()); TiXmlDocument doc(alarmFile); TiXmlHandle docHandle( &doc ); if (!doc.LoadFile()) { UtlString errorMsg; XmlErrorMsg( doc, errorMsg ); OsSysLog::add(FAC_ALARM, PRI_ERR, "Failed to load alarm file: %s", errorMsg.data()); return false; } TiXmlHandle docH( &doc ); //load alarm definitions TiXmlElement* alarmDefElement = docH.FirstChildElement("alarm_server"). FirstChildElement("definitions").Element(); if (alarmDefElement) { TiXmlElement* element = alarmDefElement->FirstChildElement(); cAlarmData* pAlarmData; for (; element; element=element->NextSiblingElement() ) { pAlarmData = new cAlarmData(); if (loadAlarmData(element, pAlarmData)) { UtlString* idStr = new UtlString(pAlarmData->getId()); if (!mAlarmMap.insertKeyAndValue(idStr, pAlarmData)) { OsSysLog::add(FAC_ALARM, PRI_ERR, "Alarm id '%s' is already defined", pAlarmData->getId().data()); delete pAlarmData; } } else { OsSysLog::add(FAC_ALARM, PRI_ERR, "Alarm element '%s' is incorrectly defined", (char *)element->ToText()); delete pAlarmData; } } } return true; }
bool PackagesInfo::Parse(wxMemoryInputStream& inputStream, muThread_Updater* thread) { m_thread = thread; /*wxTextInputStream textStream( inputStream ); do { wxString line = textStream.ReadLine(); wxLogVerbose(line); } while(textStream.GetChar() != 0);*/ TiXmlDocument doc; doc.Parse(static_cast<char*>(inputStream.GetInputStreamBuffer()->GetBufferStart())); TiXmlHandle docHandle( doc.RootElement() ); // Read format version ParseString(docHandle.FirstChild("format").FirstChild("revision").ToElement()).ToLong(&m_fileFormat); // Read format compatible ParseString(docHandle.FirstChild("format").FirstChild("compatible").ToElement()).ToLong(&m_compatibleFormat); // Read update version ParseString(docHandle.FirstChild("info").FirstChild("version").ToElement()).ToLong(&m_updateVersion); // Read update changelog m_changelog = ParseString(docHandle.FirstChild("info").FirstChild("changelog").ToElement()); // Read packages for( TiXmlNode* node = docHandle.FirstChild("package").ToNode(); node; node=node->NextSibling("package") ) { thread->PostProgress(wxT("Package")); DownloadInfo info; if( info.Parse(node, thread) ) { m_downloads.push_back(info); thread->PostProgress(wxT("Package parsed.")); } else { thread->PostProgress(wxT("Package FAILED!")); } } return true; }
Material* MaterialDatabase::openMaterialFile(std::string materialFileName) { std::string materialPath = Singleton<GlobalPaths>::Instance()->getMaterialPath(); std::string fullPath = materialPath + materialFileName + ".xml"; Material* material = new Material(); //XML loading TiXmlDocument doc; doc.LoadFile(fullPath.c_str()); if(doc.Error()) throw std::runtime_error(doc.ErrorDesc()); TiXmlHandle docHandle(&doc); TiXmlElement* materialElement = docHandle.FirstChild("material").ToElement(); material->initialize(materialElement); return material; }
bool Utils::set_config_option(std::string key, std::string value) { TiXmlDocument document(getConfigFile(LOCAL_CONFIG).c_str()); if (!document.LoadFile()) { cError() << "There was an exception in XML parsing."; cError() << "Parse error: " << document.ErrorDesc(); cError() << "In file " << getConfigFile(LOCAL_CONFIG) << " At line " << document.ErrorRow(); return false; } TiXmlHandle docHandle(&document); bool found = false; TiXmlElement *key_node = docHandle.FirstChildElement("calaos:config").FirstChildElement().ToElement(); if (key_node) { for(; key_node; key_node = key_node->NextSiblingElement()) { if (key_node->ValueStr() == "calaos:option" && key_node->Attribute("name") && key_node->Attribute("name") == key) { key_node->SetAttribute("value", value); found = true; break; } } //the option was not found, we create it if (!found) { TiXmlElement *element = new TiXmlElement("calaos:option"); element->SetAttribute("name", key); element->SetAttribute("value", value); docHandle.FirstChild("calaos:config").ToElement()->LinkEndChild(element); } document.SaveFile(); } return true; }
std::vector<double> ModNeatExperiment7::readCollisionData(string xmlCompleteFileName) { std::vector<double> returnVec; TiXmlDocument docHandle(xmlCompleteFileName); docHandle.LoadFile(); if (docHandle.Error()) { screen << "XML error. Exiting..." << endl; fflush(stdout); exit(-1); } // ugly workaround to get the 'collisions' node, because TiXML is a horriby incomplete lib. TiXmlElement * collisions = docHandle.RootElement()->FirstChildElement()->NextSiblingElement()->NextSiblingElement(); if (collisions == NULL) { screen << "collisions is NULL. Exiting..." << endl; fflush(stdout); exit(-1); } else { // add the number of total collisions double value_total; const char * total = collisions->Attribute("total", &value_total); if (total == NULL) { screen << "attribute 'total' is NULL. Exiting..." << endl; fflush(stdout); exit(-1); } returnVec.push_back(value_total); // add the total number of touch times double value_touchtime; const char * touchtime = collisions->Attribute("totaltouchtime", &value_touchtime); if (touchtime == NULL) { screen << "attribute 'totaltouchtime' is NULL. Exiting..." << endl; fflush(stdout); exit(-1); } returnVec.push_back(value_touchtime); } return returnVec; }
// \brief Read segments (and general MeshGraph) given TiXmlDocument. void MeshGraph2D::ReadGeometry(TiXmlDocument &doc) { // Read mesh first MeshGraph::ReadGeometry(doc); TiXmlHandle docHandle(&doc); TiXmlElement* mesh = NULL; /// Look for all geometry related data in GEOMETRY block. mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); ASSERTL0(mesh, "Unable to find GEOMETRY tag in file."); ReadCurves(doc); ReadEdges(doc); ReadElements(doc); ReadComposites(doc); ReadDomain(doc); }
//check for game end void GameWindow::EndGame(){ //if player is offscreen (fell into pit) if(!m_bInGame || m_wPlayer.m_Y >= kScreenHeight || m_wPlayer.m_Health <=0){ //write high score if(m_Score > m_Highscore){ TiXmlDocument doc("Data.xml"); TiXmlHandle docHandle( &doc ); bool loadOkay = doc.LoadFile(); if (loadOkay){ TiXmlElement* child = docHandle.FirstChild( "data" ).FirstChild( "scores" ).ToElement(); child->SetAttribute("best", m_Score); doc.SaveFile("Data.xml"); m_Highscore = m_Score; } } m_bInGame = false; Reset(); } }
void UISystem::ReadStyleFile(const std::string& filePath) { TiXmlDocument doc(filePath.c_str()); doc.LoadFile(); TiXmlHandle docHandle(&doc); //Get the style name and insert it into the named properties TiXmlHandle styleNameHandle = docHandle.FirstChild("Style"); TiXmlElement* styleNameElement = styleNameHandle.ToElement(); const std::string styleName = styleNameElement->Attribute("name"); FATAL_ASSERT(styleName != ""); const TiXmlNode* global = styleNameElement->FirstChild("Global"); bool hasGlobal = global != nullptr; WidgetStyle tempStyle; if (hasGlobal) { tempStyle = WidgetStyle(global); } for (const TiXmlNode* widgetDefinition = styleNameElement->FirstChild(); widgetDefinition; widgetDefinition = widgetDefinition->NextSibling()) { const char* widgetName = widgetDefinition->ToElement()->Value(); if (strcmp(widgetName, "Global") != 0) { WidgetStyle ws = tempStyle; WidgetStyle* newWs = new WidgetStyle(widgetDefinition); ws.MergeStyle(newWs); WidgetStyle* mergedWS = new WidgetStyle(ws); delete newWs; s_styles[styleName][widgetName] = mergedWS; } } auto styleMap = s_styles[styleName]; for (auto& it : s_widgetFactory) { std::string widgetName = it.first; auto found = styleMap.find(widgetName); if (found == styleMap.end()) { s_styles[styleName][widgetName] = new WidgetStyle(tempStyle); } } }
void parseAndShowResult() { std::cout << "Parsing file." << std::endl; TiXmlDocument doc("temp.xml"); doc.LoadFile(); TiXmlHandle docHandle(&doc); TiXmlElement * firstElements = docHandle.FirstChild("response").ToElement(); TiXmlElement * statusElem = 0; statusElem = firstElements->FirstChildElement(); if (!statusElem) { std::cout << "Corrupt file, wrong request made?" << std::endl; return; } if (std::string(statusElem->GetText()).compare("success") != 0) { TiXmlElement * errorElem = firstElements->FirstChildElement("error"); std::cout << "Parsing failed with message: " << errorElem->GetText() << std::endl; return; } TiXmlElement * accountElement = firstElements->FirstChild("result")->FirstChild("account")->ToElement(); TiXmlElement * nameElement = 0; nameElement = accountElement->FirstChildElement("name"); if (nameElement == 0) { std::cout << "Parsing failed, could not find 'name' element." << std::endl; return; } std::cout << "Located name: " << nameElement->GetText() << std::endl;; }
/**Parser xml extrai nomes de ficheiros que conteem os triângulos das figuras a desenhar*/ vector<string> readFromXML(string filename) { vector<string> figuras; const char * nomeFich = filename.c_str(); const char* circum; TiXmlDocument doc(nomeFich); doc.LoadFile(); TiXmlHandle docHandle(&doc); TiXmlElement * ficheiro = docHandle.FirstChild("imagem").FirstChild("modelo").ToElement(); while (ficheiro) { circum = ficheiro->Attribute("ficheiro"); figuras.push_back(string(circum)); ficheiro = ficheiro->NextSiblingElement("modelo"); } return figuras; }
bool U2FrameXmlParser::OpenXml() { U2ASSERT(!m_pXmlDoc); // Get FullPath m_pXmlDoc = new TiXmlDocument; SetFilename(m_pOwnerFrame->GetFilename()); if(m_pXmlDoc->LoadFile(m_szFullPath.Str())) { TiXmlHandle docHandle(m_pXmlDoc); TiXmlElement* pFrameXmlElem = docHandle.FirstChildElement("Frame").Element(); U2ASSERT(pFrameXmlElem); m_pOwnerFrame->SetName(pFrameXmlElem->Attribute("name")); //m_pOwnerFrame->SetShaderPath return true; } delete (m_pXmlDoc); m_pXmlDoc = NULL; return false; }
xdl_int XdevLFTDI::readInfoFromXMLFile() { if(getMediator()->getXmlFilename() == nullptr) return RET_FAILED; TiXmlDocument xmlDocument; if(!xmlDocument.LoadFile(getMediator()->getXmlFilename())) { XDEVL_MODULE_ERROR("Could not parse xml file: " << getMediator()->getXmlFilename() << std::endl); return RET_FAILED; } TiXmlHandle docHandle(&xmlDocument); TiXmlElement* root = docHandle.FirstChild(XdevLCorePropertiesName.c_str()).FirstChildElement("XdevLSerial").ToElement(); if(!root) { XDEVL_MODULE_WARNING("<XdevLSerial> section not found. Using default values for the device.\n"); return RET_SUCCESS; } while(root != nullptr) { if(root->Attribute("id")) { XdevLID id(root->Attribute("id")); if(getID() == id) { if(root->Attribute("device")) { m_deviceName = XdevLString(root->Attribute("device")); } if(root->Attribute("usb_in_size")) { std::istringstream ss(root->Attribute("usb_in_size")); ss >> m_usbInSize; } if(root->Attribute("usb_out_size")) { std::istringstream ss(root->Attribute("usb_out_size")); ss >> m_usbOutSize; } if(root->Attribute("latency_timer")) { std::istringstream ss(root->Attribute("latency_timer")); ss >> m_latencyTimer; }
/** * Get a scene from a map file in XML format. */ Scene* MapLoader::getScene(const std::string &path) { scene = new Scene(); TiXmlDocument doc(Environment::getDataDir() + "/maps/" + path + ".xml"); bool loaded = doc.LoadFile(); if (loaded) { TiXmlHandle docHandle(&doc); TiXmlElement *element = docHandle.FirstChildElement().ToElement(); rootHandle = TiXmlHandle(element); extractSpawn(); extractDoor(); extractModels(); extractLights(); extractWalls(); extractTriggers(); cout << "File loaded." << endl; } else { cout << "Unable to load file. " << endl; cout << Environment::getDataDir() << "/" << path << ".xml" << endl; } return scene; }
std::shared_ptr<Screen> XmlScreenLoader::loadScreen(const std::string &path) { XMLDocument doc(true, COLLAPSE_WHITESPACE); XMLError error = doc.LoadFile(path.c_str()); const std::string &module = XmlScreenLoader::MODULE_NAME; if (error == 0) { std::shared_ptr<Screen> screen = std::make_shared<Screen>(); //setup screen pointer XMLHandle docHandle(&doc); XMLElement *element = docHandle.FirstChildElement("screen").ToElement(); XMLHandle rootHandle = XMLHandle(element); if (not loadText(rootHandle, &screen->text)) { XmlScreenLoader::handleFailureForElement(module, std::string("text"), path); } if (not extractColor(element, &screen->color)) { XmlScreenLoader::handleFailureForElement(module, std::string("color"), path); } Util::Log(Debug, module) << "Screen " << path << " loaded"; return screen; } throw std::runtime_error("Failed to load " + path + ": " + errorName(error)); }
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 CGameMap::convertFileToMap( std::wstring path ) { std::wstring FILENAME[2] = { L"map.xml", L"TileSet" }; NNZip *xmlLoad; NNZip **tileSetLoad; // XML LOAD xmlLoad = NNResourceManager::GetInstance()->UnzipFileToMemory(path, FILENAME[0]); mMapXMLData= NNResourceManager::GetInstance()->LoadXMLFromMemory(xmlLoad); std::string tile; int usedTileSet = 0; // MapInfo { // Map Size { mWidth = atoi(mMapXMLData->XPathToString("/map/mapInfo/size/@width").c_str()); mHeight = atoi(mMapXMLData->XPathToString("/map/mapInfo/size/@height").c_str()); mTile = new CTile**[mHeight]; for(int i=0;i<mHeight; ++i) { mTile[i] = new CTile *[mWidth]; for( int j=0; j< mWidth; ++j) mTile[i][j] = CTile::Create(); } } // Used Tile Set { usedTileSet = atoi(mMapXMLData->XPathToString("/map/mapInfo/usedTileSet/@count").c_str()); tileSetLoad = new NNZip*[usedTileSet]; for(int i=0; i<usedTileSet; ++i) tileSetLoad[i] = NNResourceManager::GetInstance()->UnzipFileToMemory(path, FILENAME[1] + std::to_wstring(i)); } } // Tile Info { TiXmlHandle docHandle( mMapXMLData->GetDoc() ); TiXmlElement* child = docHandle.FirstChild( "map" ).FirstChild( "tileInfo").FirstChild("tile").ToElement(); for( child; child; child=child->NextSiblingElement() ) { int i = atoi(child->Attribute("Y")); int j = atoi(child->Attribute("X")); int tileSetIndex, x, y; TiXmlElement* tileImageInfo = child->FirstChild("TileImageInfo")->ToElement(); x = atoi(tileImageInfo->Attribute("Y")); y = atoi(tileImageInfo->Attribute("X")); tileSetIndex = atoi(tileImageInfo->Attribute("Index")); mTile[i][j]->misFull = strcmp(child->Attribute("isFull"), "true") == 0 ? true : false; TiXmlElement* tileAttribute = child->FirstChild("Attribute")->ToElement(); mTile[i][j]->mattribute = strcmp(tileAttribute->Attribute("move") , "true") == 0 ? 1 : 0; mTile[i][j]->mheight = atoi(tileAttribute->Attribute("height")); printf("%d / %d\n",i,j); TiXmlElement* tileObject = child->FirstChild("Object")->ToElement(); mTile[i][j]->mimage = NNSpriteAtlas::Create(tileSetLoad[tileSetIndex]); mTile[i][j]->AddChild(mTile[i][j]->mimage); AddChild(mTile[i][j]); mTile[i][j]->mimage->SetCutSize((float)y, (float)x, y + 64.f, x + 64.f); mTile[i][j]->mimage->SetPosition(j*64.f, i*64.f); std::string temp = tileObject->Attribute("Type"); if ( temp == "Tile" ) mTile[i][j]->mType = TILE; else if (temp == "Barrack A In") mTile[i][j]->mType = BARRACK_A; else if ( temp == "Barrack B In" ) mTile[i][j]->mType = BARRACK_B; else if ( temp == "Barrack C In" ) mTile[i][j]->mType = BARRACK_C; else if ( temp == "Barrack D In" ) mTile[i][j]->mType = BARRACK_D; else if ( temp == "Barrack Out" ) mTile[i][j]->mType = BARRACK_OUT; else if ( temp == "A Team Starting Point" ) mTile[i][j]->mType = STARTING_POINT_A; else if ( temp == "B Team Starting Point" ) mTile[i][j]->mType = STARTING_POINT_B; NNAnimation *Gate = CreateBarrackGate(mTile[i][j]->mType); if (Gate != nullptr) { Gate->SetPosition(j*64.f, i*64.f); AddChild(Gate); } } } delete tileSetLoad; }
std::tstring ContainerManager::GetContainerName(unsigned int charid, unsigned int containerid) const { if (containerid == 1) { return _T("Bank"); } else if (containerid == 2) { return _T("Inventory/Equip"); } else if (containerid == 3) { return _T("Shop"); } std::tstring result; __int64 key = ((__int64)charid) << 32; key += containerid; FILETIME lastWrite; lastWrite.dwHighDateTime = lastWrite.dwLowDateTime = 0; std::tstring filename; for (unsigned int i = 0; i < m_accounts.size(); i++) { filename = STREAM2STR( AOManager::instance().getAOPrefsFolder() << _T("\\") << m_accounts[i] << _T("\\Char") << charid << _T("\\Containers\\Container_51017x") << containerid << _T(".xml") ); if (PathFileExists(filename.c_str())) { WIN32_FILE_ATTRIBUTE_DATA atribs; if (GetFileAttributesEx(filename.c_str(), GetFileExInfoStandard, &atribs)) { lastWrite = atribs.ftLastWriteTime; break; } } } bool wasInCache = m_containerFileCache.find(key) != m_containerFileCache.end(); // Clear invalid cache if ((filename.empty() || (lastWrite.dwHighDateTime == 0 && lastWrite.dwHighDateTime == 0)) && wasInCache) { m_containerFileCache.erase(m_containerFileCache.find(key)); } // Create cache from file if (!filename.empty()) { bool update = true; // If already in cache, check timestamps if (m_containerFileCache.find(key) != m_containerFileCache.end()) { FILETIME stamp = m_containerFileCache[key].second; if (stamp.dwHighDateTime == lastWrite.dwHighDateTime && stamp.dwLowDateTime == lastWrite.dwLowDateTime) { update = false; result = m_containerFileCache[key].first; } } if (update) { TiXmlDocument document; if (document.LoadFile(to_ascii_copy(filename), TIXML_ENCODING_UTF8)) { TiXmlHandle docHandle( &document ); TiXmlElement* element = docHandle.FirstChild( "Archive" ).FirstChild( "String" ).Element(); while (element) { if (StrCmpA(element->Attribute("name"), "container_name") == 0) { result = from_utf8_copy(element->Attribute("value")); boost::algorithm::replace_all(result, _T("&"), _T("&")); // Fixes wierd encoding in the AO xml. m_containerFileCache[key] = std::pair<std::tstring, FILETIME>(result, lastWrite); break; } element = element->NextSiblingElement(); } } } } if (result.empty()) { result = MakeContainerName(charid, containerid); } return result; }
bool Module::init(const std::string &strModuleText, int argc, char **argv, bool bStrictParse) { m_argc = argc; m_argv = argv; loop = new PortComm(NULL); std::string strConfigFile; // allocate option on heap (no delete on purpose) flowvr::utils::Option<std::string> *portFile = new flowvr::utils::Option<std::string>("portfile", 'p', "path to the module parameter file", false); flowvr::utils::Option<bool> *dgbWait = new flowvr::utils::Option<bool>("dbgWait", 'd', "wait infinite to have a debugger attached", false, true); flowvr::utils::Option<bool> *initWait = new flowvr::utils::Option<bool>("initWait", 'd', "wait infinite to have a debugger attached (init routine)", false, true); flowvr::utils::Option<std::string> *idstring = new flowvr::utils::Option<std::string>("idstring", 'i', "id string passed from flowvr-app", true); flowvr::utils::Option<std::string> *argtree = new flowvr::utils::Option<std::string>("argtree", 'a', "base64 encoded / bzip2 compressed arguments", false); flowvr::utils::CmdLine line(std::string(argv[0]) + strModuleText ); bool bError=false; if(line.parse( argc, argv, &bError ) == false and bError == false ) { // help option std::cout << line.help() << std::endl; return false; } if((*portFile).count == 0) { // ok, we can stop here... we NEED a portfile declaration if( idstring->count == 0 ) std::cerr << "no portfile specified. STOP." << std::endl; else std::cerr << "[" << idstring->value() << "] -- no portfile specified. STOP." << std::endl; return false; } if( (*initWait).value() == true ) { std::cerr << "PortComm::setInifiteWaitFlag() during init for [" << getpid() << "]-- ATTENTION" << std::endl; bool b = true; while(b) { flowvr::utils::microsleep(1000); } } // cache value, as the upcoming parsing might reset that it was already written, // so we lose the value on the second parsing std::string strIdTag = idstring->value(); std::string argT = argtree->value(); std::string pFile( (*portFile).value() ); if( !descFiles.exists( pFile ) ) { if(!descFiles.findFile( pFile )) { std::cerr << " ** could not resolve portfile [" << pFile << "]" << std::endl; return false; } } flowvr::xml::TiXmlDocument config( pFile.c_str() ); if( config.LoadFile() ) { // configure plugins first flowvr::xml::TiXmlHandle docHandle( &config ); flowvr::xml::TiXmlHandle configNode = docHandle.FirstChild("config"); flowvr::xml::TiXmlHandle xmlServices = configNode.FirstChild("services"); flowvr::xml::TiXmlHandle ports = configNode.FirstChild("ports"); flowvr::xml::TiXmlHandle xmlPlugs = configNode.FirstChild("plugins"); flowvr::xml::TiXmlHandle code = configNode.FirstChild("code"); flowvr::xml::TiXmlHandle stampsConf = configNode.FirstChild("stamplists"); std::map<std::string, flowvr::Port*> mpPorts; std::vector<flowvr::Port*> vePorts; flowvr::portutils::ARGS argmap; std::string::size_type n = argT.find_first_of(':', 0); if( !n or n == std::string::npos ) { std::cerr << argtree->count << ": argtree given, but no size prefix!" << std::endl << "argtree = " << argtree->value() << std::endl; argmap["services"] = flowvr::portutils::Parameter( flowvr::portutils::ParameterContainer() ); argmap["plugins"] = flowvr::portutils::Parameter( flowvr::portutils::ParameterContainer() ); argmap["module"] = flowvr::portutils::Parameter( flowvr::portutils::ParameterContainer() ); } else { std::string sb64( argT.begin()+n+1, argT.end() ); std::string sSize( argT.begin(), argT.begin()+n); flowvr::portutils::ARGS::fromBase64(sb64, argmap, atol(sSize.c_str()) ); } flowvr::portutils::configureServiceLayers( xmlServices, services ); // create argument listings flowvr::portutils::prepareServices( services ); flowvr::portutils::createServices(services, *this, argmap["services"].getSubContainerConstRef()); flowvr::portutils::configurePlugins(xmlPlugs, services, plugs, argmap["plugins"].getSubContainerConstRef() ); // load the stamp list for this configuration. // the stamp list is expected to reside in the very same directory // as the portfile itself, so we look for the prefix in the path given // for the portfile. std::string strPrefix; std::string::size_type np = pFile.find_last_of("/"); // is it like: /<path>/<path>/ if( np != std::string::npos ) { // yes... prefixed with a relative or absolute path strPrefix = pFile.substr(0,np+1); // include slash } // else: no, its probably in the same directory, so prefix will be empty. flowvr::portutils::configureStampMap( stampsConf, stampMap, "", strPrefix ); flowvr::portutils::configurePorts( ports, stampMap, mpPorts, vePorts, argmap["module"].getSubContainerConstRef() ); flowvr::portutils::configurePortComm( code, mpPortComms, mpPorts, plugs ); flowvr = flowvr::initModule( vePorts ); } else { std::cerr << "could not load port-config file given as [" << pFile << "]" << std::endl; const char *pcErr = config.ErrorDesc(); if(pcErr) std::cerr << "row: " << config.ErrorRow() << std::endl << "col: " << config.ErrorCol() << std::endl << "err: " << pcErr << std::endl; return false; } if((*dgbWait).value()) (*loop).setInfiniteWaitFlag(); std::vector<IServiceLayer*> v; for(SERV::const_iterator cit = services.begin(); cit != services.end(); ++cit ) { if( (*cit).second.m_layer ) v.push_back( (*cit).second.m_layer ); } (*loop).setServices(v); (*loop).setCodeRange( mpPortComms ); (*loop).setModuleAPI(flowvr); (*loop).setDefaultReturn(flowvr::portutils::PortComm::RET_FAIL); if( flowvr ) { std::for_each( v.begin(), v.end(), std::mem_fun( &flowvr::portutils::IServiceLayer::Once ) ); for( std::vector<PortComm::PortMap>::iterator it = mpPortComms.begin(); it != mpPortComms.end(); ++it ) (*it).once(flowvr); } return true; }
/** * Read global optimisation parameters from a file and set up flags. * @param fileName File to read parameters from. */ GlobalOptParam::GlobalOptParam(const LibUtilities::SessionReaderSharedPtr& pSession, const int dim, const Array<OneD, const int> &NumShapeElements): m_doGlobalMatOp(SIZE_OptimizeOperationType,false) { int i; int numShapes = 0; TiXmlDocument& doc = pSession->GetDocument(); m_shapeNumElements = NumShapeElements; switch (dim) { case 1: numShapes = 1; ASSERTL0(false,"Needs setting up for dimension 1"); break; case 2: numShapes = 2; m_shapeList = Array<OneD, LibUtilities::ShapeType>(numShapes); m_shapeList[0] = LibUtilities::eTriangle; m_shapeList[1] = LibUtilities::eQuadrilateral; break; case 3: numShapes = 4; m_shapeList = Array<OneD, LibUtilities::ShapeType>(numShapes); m_shapeList[0] = LibUtilities::eTetrahedron; m_shapeList[1] = LibUtilities::ePyramid; m_shapeList[2] = LibUtilities::ePrism; m_shapeList[3] = LibUtilities::eHexahedron; break; } m_doBlockMatOp = Array<OneD, Array<OneD,bool> > (SIZE_OptimizeOperationType); for(i = 0; i < SIZE_OptimizeOperationType; ++i) { m_doBlockMatOp[i] = Array<OneD, bool> (numShapes,false); } TiXmlHandle docHandle(&doc); TiXmlElement* master = docHandle.FirstChildElement("NEKTAR").Element(); ASSERTL0(master , "Unable to find NEKTAR tag in file."); TiXmlElement* paramList = docHandle.FirstChildElement("NEKTAR") .FirstChildElement("GLOBALOPTIMIZATIONPARAMETERS") .Element(); // If no global optimisation parameters set, we're done if (!paramList) { return; } // Check if there is a reference an external file and if so, load it TiXmlElement* source = paramList->FirstChildElement("SOURCE"); if (source) { std::string sourceFile = source->Attribute("FILE"); TiXmlDocument docSource; bool loadOkay = docSource.LoadFile(sourceFile); ASSERTL0(loadOkay, (std::string("Unable to load file: ") + sourceFile).c_str()); TiXmlHandle docSourceHandle(&docSource); master = docHandle.FirstChildElement("NEKTAR").Element(); ASSERTL0(master , "Unable to find NEKTAR tag in file."); paramList = docHandle.FirstChildElement("NEKTAR") .FirstChildElement("GLOBALOPTIMIZATIONPARAMETERS") .Element(); ASSERTL0(paramList, std::string("Specified source file '" + sourceFile + "' is missing an " "GLOBALOPTIMIZATIONPARAMETERS tag.").c_str()); } int n; for(n = 0; n < SIZE_OptimizeOperationType; n++) { TiXmlElement* operationType = paramList->FirstChildElement( OptimizationOperationTypeMap[n]); if(operationType) { TiXmlElement* arrayElement = operationType ->FirstChildElement("DO_GLOBAL_MAT_OP"); if(arrayElement) { int value; int err; err = arrayElement->QueryIntAttribute("VALUE", &value); ASSERTL0(err == TIXML_SUCCESS,( std::string("Unable to read DO_GLOBAL_MAT_OP " "attribute VALUE for ") + std::string(OptimizationOperationTypeMap[n]) + std::string(".") )); m_doGlobalMatOp[n] = (bool) value; } arrayElement = operationType->FirstChildElement("DO_BLOCK_MAT_OP"); if(arrayElement) { int value; int err; switch (dim) { case 1: break; case 2: err = arrayElement->QueryIntAttribute("TRI", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute TRI for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][0] = (bool) value; err = arrayElement->QueryIntAttribute("QUAD", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute QUAD for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][1] = (bool) value; break; case 3: err = arrayElement->QueryIntAttribute("TET", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute TET for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][0] = (bool) value; err = arrayElement->QueryIntAttribute("PYR", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute PYR for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][1] = (bool) value; err = arrayElement->QueryIntAttribute("PRISM", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute PRISM for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][2] = (bool) value; err = arrayElement->QueryIntAttribute("HEX", &value); ASSERTL0(err == TIXML_SUCCESS, ( std::string("Unable to read DO_BLOCK_MAT_OP " "attribute HEX for ") + std::string(OptimizationOperationTypeMap[n]) + std::string("."))); m_doBlockMatOp[n][3] = (bool) value; break; break; } } } } }
//------------------------------------------------------------------------------------------------- bool U2FrameXmlParser::Parse() { TiXmlHandle docHandle(m_pXmlDoc); TiXmlElement* pFrameElem = docHandle.FirstChildElement("Frame").Element(); U2ASSERT(pFrameElem); TiXmlElement* pChild; for(pChild = pFrameElem->FirstChildElement(); pChild; pChild = pChild->NextSiblingElement()) { #ifdef UNICODE if(ToUnicode(pChild->Value()) == U2DynString(_T("Shaders"))) { ParseShaders(); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("RenderTarget"))) { ParseRenderTarget(pChild, m_pOwnerFrame); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("Float"))) { ParseGlobalVariable(U2Variable::Float, pChild, m_pOwnerFrame); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("Float4"))) { ParseGlobalVariable(U2Variable::Vector4, pChild, m_pOwnerFrame); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("Int"))) { ParseGlobalVariable(U2Variable::Int, pChild, m_pOwnerFrame); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("Texture"))) { ParseGlobalVariable(U2Variable::Object, pChild, m_pOwnerFrame); } else if(ToUnicode(pChild->Value()) == U2DynString(_T("RenderTarget"))) { ParseFrameSection(pChild, m_pOwnerFrame); } #else if(pChild->Value() == U2DynString(_T("Shaders"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseShaders(); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseShaders: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("RenderTarget"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseRenderTarget(pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseRenderTarget: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("Float"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseGlobalVariable(U2Variable::Float, pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseGlobalVariable Float: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("Float4"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseGlobalVariable(U2Variable::Vector4, pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseGlobalVariable Float4: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("Int"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseGlobalVariable(U2Variable::Int, pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseGlobalVariable Int: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("Texture"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); ParseGlobalVariable(U2Variable::Object, pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseGlobalVariable Texture: ") << prof.GetTimeInSecs(); } else if(pChild->Value() == U2DynString(_T("FrameSection"))) { PROFILER_DECLARE(prof); PROFILER_START(prof); // Reset 에러... 2011/09/26 ParseFrameSection(pChild, m_pOwnerFrame); PROFILER_STOP(prof); //FILE_LOG(logINFO) << _T("ParseFrameSection: ") << prof.GetTimeInSecs(); } #endif } return true; }
bool cAlarmServer::loadAlarmStringsFile(const UtlString& stringsFile) { OsSysLog::add(FAC_ALARM, PRI_DEBUG, " load alarm strings file %s", stringsFile.data()); TiXmlDocument doc(stringsFile); TiXmlHandle docHandle( &doc ); if (!doc.LoadFile()) { UtlString errorMsg; XmlErrorMsg( doc, errorMsg ); OsSysLog::add(FAC_ALARM, PRI_ERR, "failed to load alarm strings file: %s", errorMsg.data()); return false; } TiXmlHandle docH( &doc ); TiXmlHandle alarmServerHandle = docH.FirstChildElement("alarm_server"); TiXmlElement* settingsElement = alarmServerHandle.FirstChildElement("settings").Element(); if (settingsElement) { //load alarm action strings TiXmlElement* alarmActionsElement = settingsElement->FirstChildElement("actions"); if (alarmActionsElement) { TiXmlElement* element = alarmActionsElement->FirstChildElement("log"); if (mpNotifiers[cAlarmData::eActionLog]) { mpNotifiers[cAlarmData::eActionLog]->initStrings(element); } element = alarmActionsElement->FirstChildElement("email"); if (mpNotifiers[cAlarmData::eActionEmail]) { mpNotifiers[cAlarmData::eActionEmail]->initStrings(element); } element = alarmActionsElement->FirstChildElement("sms"); if (mpNotifiers[cAlarmData::eActionSms]) { mpNotifiers[cAlarmData::eActionSms]->initStrings(element); } /* Not implemented as Strings are not needed for TrapNotifier. element = alarmActionsElement->FirstChildElement("trap"); if (mpNotifiers[cAlarmData::eActionTrap]) { mpNotifiers[cAlarmData::eActionTrap]->initStrings(element); } */ } } else { OsSysLog::add(FAC_ALARM, PRI_DEBUG, "no <settings> element in alarm config file '%s'", stringsFile.data()); } //load alarm description strings TiXmlElement* alarmDefElement = alarmServerHandle. FirstChildElement("definitions").Element(); if (alarmDefElement) { TiXmlElement* element = alarmDefElement->FirstChildElement(); UtlString idStr; UtlString descStr; UtlString resStr; for (; element; element=element->NextSiblingElement() ) { idStr = element->Attribute("id"); if (idStr.isNull()) { OsSysLog::add(FAC_ALARM, PRI_ERR,"Parsing alarm strings file %s: alarm ID is required", stringsFile.data()); continue; } cAlarmData* alarmData = lookupAlarm(idStr); if (!alarmData) { OsSysLog::add(FAC_ALARM, PRI_ERR,"unknown alarm ID %s", idStr.data()); continue; } TiXmlElement* codeElement = element->FirstChildElement("shorttitle"); if (codeElement) { textContentShallow(descStr, codeElement); if (!descStr.isNull()) { UtlString tempStr; XmlUnEscape(tempStr, descStr); alarmData->setShortTitle(tempStr); } } codeElement = element->FirstChildElement("description"); if (codeElement) { textContentShallow(descStr, codeElement); if (!descStr.isNull()) { UtlString tempStr; XmlUnEscape(tempStr, descStr); alarmData->setDescription(tempStr); } } codeElement = element->FirstChildElement("resolution"); if (codeElement) { textContentShallow(resStr, codeElement); if (!resStr.isNull()) { UtlString tempStr; XmlUnEscape(tempStr, resStr); alarmData->setResolution(tempStr); } } } } return true; }
std::vector<itk::SmartPointer<mitk::BaseData>> mitk::GeometryDataReaderService::Read() { // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); std::vector<itk::SmartPointer<BaseData>> result; InputStream stream(this); TiXmlDocument doc; stream >> doc; if (!doc.Error()) { TiXmlHandle docHandle(&doc); for (TiXmlElement *geomDataElement = docHandle.FirstChildElement("GeometryData").ToElement(); geomDataElement != nullptr; geomDataElement = geomDataElement->NextSiblingElement()) { for (TiXmlElement *currentElement = geomDataElement->FirstChildElement(); currentElement != nullptr; currentElement = currentElement->NextSiblingElement()) { // different geometries could have been serialized from a GeometryData // object: std::string tagName = currentElement->Value(); if (tagName == "Geometry3D") { Geometry3D::Pointer restoredGeometry = Geometry3DToXML::FromXML(currentElement); if (restoredGeometry.IsNotNull()) { GeometryData::Pointer newGeometryData = GeometryData::New(); newGeometryData->SetGeometry(restoredGeometry); result.push_back(newGeometryData.GetPointer()); } else { MITK_ERROR << "Invalid <Geometry3D> tag encountered. Skipping."; } } else if (tagName == "ProportionalTimeGeometry") { ProportionalTimeGeometry::Pointer restoredTimeGeometry = ProportionalTimeGeometryToXML::FromXML(currentElement); if (restoredTimeGeometry.IsNotNull()) { GeometryData::Pointer newGeometryData = GeometryData::New(); newGeometryData->SetTimeGeometry(restoredTimeGeometry); result.push_back(newGeometryData.GetPointer()); } else { MITK_ERROR << "Invalid <ProportionalTimeGeometry> tag encountered. Skipping."; } } } // for child of <GeometryData> } // for <GeometryData> } else { mitkThrow() << "Parsing error at line " << doc.ErrorRow() << ", col " << doc.ErrorCol() << ": " << doc.ErrorDesc(); } if (result.empty()) { mitkThrow() << "Did not read a single GeometryData object from input."; } return result; }