TiXmlDocument* loadFromFile(const char *filename) { // this initialize the library and check potential ABI mismatches // between the version it was compiled for and the actual shared // library used. // TiXmlDocument* doc = new TiXmlDocument; // the resulting document tree // xmlSubstituteEntitiesDefault(1); if (!(doc->LoadFile(filename))) { std::cerr << "Failed to open " << filename << "\n" << doc->ErrorDesc() << " at line " << doc->ErrorRow() << " row " << doc->ErrorCol() << std::endl; delete doc; return NULL; } return doc; }
CDLTransformRcPtr CDLTransform::CreateFromFile(const char * src, const char * cccid_) { if(!src || (strlen(src) == 0) ) { std::ostringstream os; os << "Error loading CDL xml. "; os << "Source file not specified."; throw Exception(os.str().c_str()); } std::string cccid; if(cccid_) cccid = cccid_; // Check cache AutoMutex lock(g_cacheMutex); // Use g_cacheSrcIsCC as a proxy for if we have loaded this source // file already (in which case it must be in cache, or an error) StringBoolMap::iterator srcIsCCiter = g_cacheSrcIsCC.find(src); if(srcIsCCiter != g_cacheSrcIsCC.end()) { // If the source file is known to be a pure ColorCorrection element, // null out the cccid so its ignored. if(srcIsCCiter->second) cccid = ""; // Search for the cccid by name CDLTransformMap::iterator iter = g_cache.find(GetCDLLocalCacheKey(src, cccid)); if(iter != g_cache.end()) { return iter->second; } // Search for cccid by index int cccindex=0; if(StringToInt(&cccindex, cccid.c_str(), true)) { iter = g_cache.find(GetCDLLocalCacheKey(src, cccindex)); if(iter != g_cache.end()) { return iter->second; } } std::ostringstream os; os << "The specified cccid/cccindex '" << cccid; os << "' could not be loaded from the src file '"; os << src; os << "'."; throw Exception (os.str().c_str()); } // Try to read all ccs from the file, into cache std::ifstream istream(src); if(istream.fail()) { std::ostringstream os; os << "Error could not read CDL source file '" << src; os << "'. Please verify the file exists and appropriate "; os << "permissions are set."; throw Exception (os.str().c_str()); } // Read the file into a string. std::ostringstream rawdata; rawdata << istream.rdbuf(); std::string xml = rawdata.str(); if(xml.empty()) { std::ostringstream os; os << "Error loading CDL xml. "; os << "The specified source file, '"; os << src << "' appears to be empty."; throw Exception(os.str().c_str()); } TiXmlDocument doc; doc.Parse(xml.c_str()); if(doc.Error()) { std::ostringstream os; os << "Error loading CDL xml from file '"; os << src << "'. "; os << doc.ErrorDesc() << " (line "; os << doc.ErrorRow() << ", character "; os << doc.ErrorCol() << ")"; throw Exception(os.str().c_str()); } if(!doc.RootElement()) { std::ostringstream os; os << "Error loading CDL xml from file '"; os << src << "'. "; os << "Please confirm the xml is valid."; throw Exception(os.str().c_str()); } std::string rootValue = doc.RootElement()->Value(); if(rootValue == "ColorCorrection") { // Load a single ColorCorrection into the cache CDLTransformRcPtr cdl = CDLTransform::Create(); LoadCDL(cdl.get(), doc.RootElement()->ToElement()); cccid = ""; g_cacheSrcIsCC[src] = true; g_cache[GetCDLLocalCacheKey(src, cccid)] = cdl; } else if(rootValue == "ColorCorrectionCollection") { // Load all CCs from the ColorCorrectionCollection // into the cache CDLTransformMap transformMap; CDLTransformVec transformVec; GetCDLTransforms(transformMap, transformVec, doc.RootElement()); if(transformVec.empty()) { std::ostringstream os; os << "Error loading ccc xml. "; os << "No ColorCorrection elements found in file '"; os << src << "'."; throw Exception(os.str().c_str()); } g_cacheSrcIsCC[src] = false; // Add all by transforms to cache // First by index, then by id for(unsigned int i=0; i<transformVec.size(); ++i) { g_cache[GetCDLLocalCacheKey(src, i)] = transformVec[i]; } for(CDLTransformMap::iterator iter = transformMap.begin(); iter != transformMap.end(); ++iter) { g_cache[GetCDLLocalCacheKey(src, iter->first)] = iter->second; } } // The all transforms should be in the cache. Look it up, and try // to return it. { // Search for the cccid by name CDLTransformMap::iterator iter = g_cache.find(GetCDLLocalCacheKey(src, cccid)); if(iter != g_cache.end()) { return iter->second; } // Search for cccid by index int cccindex=0; if(StringToInt(&cccindex, cccid.c_str(), true)) { iter = g_cache.find(GetCDLLocalCacheKey(src, cccindex)); if(iter != g_cache.end()) { return iter->second; } } std::ostringstream os; os << "The specified cccid/cccindex '" << cccid; os << "' could not be loaded from the src file '"; os << src; os << "'."; throw Exception (os.str().c_str()); } }
bool Scene::Unserialize( const char* filename ) { #if TINYXML_FOUND #if COMPRESSED_XML TiXmlDocument doc( filename ); if ( !doc.LoadFile() ) { printf("XML ERROR: %s, Line %i, Col %i\n", doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol() ); return false; } #else TiXmlDocument doc; /* Should handle files with and without gz compression. */ { char* xml = NULL; unsigned int size; mstl::GzFileRead( filename, xml, size ); doc.Parse( xml ); /* FIXME: GzRead allocator should provide deallocator. */ delete xml; } #endif if ( doc.Error() ) { printf("XML ERROR: %s, Line %i, Col %i\n", doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol() ); return false; } TiXmlElement* root = doc.RootElement(); if (!root) { printf("Couldn't find document root!\n"); return false; } TiXmlElement* child = root->FirstChildElement(); for( ; child; child = child->NextSiblingElement() ) { const char* s = child->Value(); printf("<%s>\n", s); if ( mCameras.GetType() == s ) { Camera* node = new Camera( child->Attribute( "name" ) ); node->Unserialize( child ); Add( node ); } else if ( mLights.GetType() == s ) { Light* node = new Light( child->Attribute( "name" ) ); node->Unserialize( child ); Add( node ); } else if ( mMeshes.GetType() == s ) { Mesh* node = new Mesh( child->Attribute( "name" ) ); node->Unserialize( child ); Add( node ); } else if ( mMetadata.GetType() == s ) { Metadata* node = new Metadata( child->Attribute( "name" ) ); node->Unserialize( child ); Add( node ); } else if ( mSkeletons.GetType() == s ) { Skeleton* node = new Skeleton( child->Attribute( "name" ) ); node->Unserialize( child ); Add( node ); } } return false; #else return false; #endif }
static void run(int argc, const char* argv[]) { PO po; PO::Option& inputOpt = po.add("input").requiresValue("<filename>"); PO::Option& widgetId = po.add("widgetid").requiresValue("<id>"); PO::Option& prefH = po.add("pref-h"); PO::Option& prefCpp = po.add("pref-cpp"); PO::Option& theme = po.add("theme"); PO::Option& strings = po.add("strings"); PO::Option& commandIds = po.add("command-ids"); PO::Option& widgetsDir = po.add("widgets-dir").requiresValue("<dir>"); PO::Option& stringsDir = po.add("strings-dir").requiresValue("<dir>"); PO::Option& guiFile = po.add("gui-file").requiresValue("<filename>"); po.parse(argc, argv); // Try to load the XML file TiXmlDocument* doc = nullptr; std::string inputFilename = po.value_of(inputOpt); if (!inputFilename.empty() && base::get_file_extension(inputFilename) == "xml") { base::FileHandle inputFile(base::open_file(inputFilename, "rb")); doc = new TiXmlDocument(); doc->SetValue(inputFilename.c_str()); if (!doc->LoadFile(inputFile.get())) { std::cerr << doc->Value() << ":" << doc->ErrorRow() << ":" << doc->ErrorCol() << ": " << "error " << doc->ErrorId() << ": " << doc->ErrorDesc() << "\n"; throw std::runtime_error("invalid input file"); } } if (doc) { // Generate widget class if (po.enabled(widgetId)) gen_ui_class(doc, inputFilename, po.value_of(widgetId)); // Generate preference header file else if (po.enabled(prefH)) gen_pref_header(doc, inputFilename); // Generate preference c++ file else if (po.enabled(prefCpp)) gen_pref_impl(doc, inputFilename); // Generate theme class else if (po.enabled(theme)) gen_theme_class(doc, inputFilename); } // Generate strings.ini.h file else if (po.enabled(strings)) { gen_strings_class(inputFilename); } // Generate command_ids.ini.h file else if (po.enabled(commandIds)) { gen_command_ids(inputFilename); } // Check all translation files (en.ini, es.ini, etc.) else if (po.enabled(widgetsDir) && po.enabled(stringsDir)) { check_strings(po.value_of(widgetsDir), po.value_of(stringsDir), po.value_of(guiFile)); } }
XMLException::XMLException(const TiXmlDocument& doc) throw () : m_errorInfo(doc.ErrorId(), doc.ErrorRow(), doc.ErrorCol()) { _createErrorString(); }
bool cSubMenu::LoadXml(const char *fname) { TiXmlDocument xmlDoc = TiXmlDocument(fname ); TiXmlElement *root = NULL; cSubMenuNode *node = NULL; bool ok =true; //Clear previously loaded Menu if (_fname!= NULL ) free(_fname); _menuTree.Clear(); _fname = strdup(fname); if ((ok=xmlDoc.LoadFile())) { if ((root = xmlDoc.FirstChildElement("menus" ))!=NULL ) { char *tmp=NULL; if ((tmp =(char*)root->Attribute("suffix"))==NULL) //asprintf(&_menuSuffix, " ..."); // set default menuSuffix asprintf(&_menuSuffix, ""); // set default menuSuffix else asprintf(&_menuSuffix, tmp); if ((root = root->FirstChildElement()) != NULL) { do { try { node = new cSubMenuNode(root, 0, &_menuTree, NULL); _menuTree.Add(node); } catch (char *message) { esyslog("ERROR: while decoding XML Node"); ok=false; } } while(ok==true && (root=root->NextSiblingElement()) !=NULL); //addMissingPlugins(); removeUndefinedNodes(); } } else { esyslog("ERROR: in %s, missing Tag <menus>\n", fname); ok=false; } } else { esyslog("ERROR: in %s : %s Col=%d Row=%d\n", fname, xmlDoc.ErrorDesc(), xmlDoc.ErrorCol(), xmlDoc.ErrorRow()); ok=false; } return ok; }
bool Config::Load() { TiXmlDocument *mDoc; TiXmlElement *mRoot; TiXmlElement *mElem; TiXmlElement *mel, *mels; boost::filesystem::path p; p = boost::filesystem::path(mFileName); if(!boost::filesystem::is_regular_file(p)) { exit("does not regular file: "+mFileName); } std::clog<<"config file: "<<mFileName<<std::endl; mIsInited = false; mDoc = new TiXmlDocument(mFileName); if(!mDoc) { exit("does not found config file: "+mFileName); } if(!mDoc->LoadFile()) { std::clog<<"load file: "<<mFileName <<" error: "<<mDoc->ErrorDesc() <<" row: "<<mDoc->ErrorRow() <<" col: "<<mDoc->ErrorCol() <<". exit." <<std::endl; ::exit(1); } if(p.has_parent_path()) { cfgFilePath = p.parent_path().string() + "/"; } else { cfgFilePath = "./"; } #ifdef DEBUG std::cout<<"config path: "<<cfgFilePath<<std::endl; #endif // DEBUG mRoot = mDoc->FirstChildElement("root"); if(!mRoot) { exit("does not found root section in file: "+mFileName); } instanceId = atoi(mRoot->Attribute("id")); //main config if( (mElem = mRoot->FirstChildElement("server")) ) { if( (mel = mElem->FirstChildElement("ip")) && (mel->GetText()) ) { server_ip_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("geocity_path")) && (mel->GetText()) ) { geocity_path_ = mel->GetText(); if(!checkPath(geocity_path_, false, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("socket_path")) && (mel->GetText()) ) { server_socket_path_ = mel->GetText(); if(!checkPath(server_socket_path_, true, true, mes)) { exit(mes); } if(boost::filesystem::exists(server_socket_path_)) { unlink(server_socket_path_.c_str()); } } if( (mel = mElem->FirstChildElement("children")) && (mel->GetText()) ) { server_children_ = atoi(mel->GetText()); } if( (mel = mElem->FirstChildElement("lock_file")) && (mel->GetText()) ) { lock_file_ = mel->GetText(); if(!checkPath(lock_file_,true, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("pid_file")) && (mel->GetText()) ) { pid_file_ = mel->GetText(); if(!checkPath(pid_file_,true, true, mes)) { exit(mes); } } if( (mel = mElem->FirstChildElement("user")) && (mel->GetText()) ) { user_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("templates")) ) { if( (mels = mel->FirstChildElement("out")) && (mels->GetText()) ) { if(!checkPath(cfgFilePath + mels->GetText(),false,true, mes)) { exit(mes); } template_out_ = getFileContents(cfgFilePath + mels->GetText()); } else { exit("element template_out is not inited"); } if( (mels = mel->FirstChildElement("error")) && (mels->GetText()) ) { if(!checkPath(cfgFilePath + mels->GetText(),false,true, mes)) { exit(mes); } template_error_ = getFileContents(cfgFilePath + mels->GetText()); } else { exit("element template_error is not inited"); } } if( (mel = mElem->FirstChildElement("cookie")) ) { if( (mels = mel->FirstChildElement("name")) && (mels->GetText()) ) cookie_name_ = mels->GetText(); else { Log::warn("element cookie_name is not inited"); } if( (mels = mel->FirstChildElement("domain")) && (mels->GetText()) ) cookie_domain_ = mels->GetText(); else { Log::warn("element cookie_domain is not inited"); } if( (mels = mel->FirstChildElement("path")) && (mels->GetText()) ) cookie_path_ = mels->GetText(); else { Log::warn("element cookie_path is not inited"); } } if( (mel = mElem->FirstChildElement("mq_path")) && (mel->GetText()) ) { mq_path_ = mel->GetText(); } if( (mel = mElem->FirstChildElement("sqlite")) ) { if( (mels = mel->FirstChildElement("db")) && (mels->GetText()) ) { dbpath_ = mels->GetText(); if(dbpath_!=":memory:" && !checkPath(dbpath_,true, true, mes)) { exit(mes); } } else { Log::warn("element db is not inited: :memory:"); dbpath_ = ":memory:"; } if( (mels = mel->FirstChildElement("schema")) && (mels->GetText()) ) { db_dump_path_ = cfgFilePath + mels->GetText(); if(!checkPath(db_dump_path_,false, false, mes)) { exit(mes); } } } } else { exit("no server section in config file. exit"); } if( (mElem = mRoot->FirstChildElement("retargeting")) ) { int redis_retargeting_ttl = REDIS_DEFAULT_TTL; if( (mel = mElem->FirstChildElement("ttl")) && (mel->GetText()) ) { redis_retargeting_ttl = strtol(mel->GetText(),NULL,10); } for(mel = mElem->FirstChildElement("redis"); mel; mel = mel->NextSiblingElement()) { if( (mels = mel->FirstChildElement("host")) && (mels->GetText()) ) { redis_server srv; srv.host = mels->GetText(); srv.ttl = redis_retargeting_ttl; if( (mels = mel->FirstChildElement("port")) && (mels->GetText()) ) { srv.port = mels->GetText(); } redis_retargeting_.push_back(srv); } } } else { exit("no section: retargeting"); } if( (mElem = mRoot->FirstChildElement("short_term")) ) { int redis_short_term_ttl = REDIS_DEFAULT_TTL; if( (mel = mElem->FirstChildElement("ttl")) && (mel->GetText()) ) { redis_short_term_ttl = strtol(mel->GetText(),NULL,10); } for(mel = mElem->FirstChildElement("redis"); mel; mel = mel->NextSiblingElement()) { if( (mels = mel->FirstChildElement("host")) && (mels->GetText()) ) { redis_server srv; srv.host = mels->GetText(); srv.ttl = redis_short_term_ttl; if( (mels = mel->FirstChildElement("port")) && (mels->GetText()) ) { srv.port = mels->GetText(); } redis_short_term_.push_back(srv); } } } else { exit("no section: short_term"); } if( (mels = mRoot->FirstChildElement("mongo")) ) { if( (mel = mels->FirstChildElement("main")) ) { for(mElem = mel->FirstChildElement("host"); mElem; mElem = mElem->NextSiblingElement("host")) { mongo_main_host_.push_back(mElem->GetText()); } if( (mElem = mel->FirstChildElement("db")) && (mElem->GetText()) ) mongo_main_db_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("set")) && (mElem->GetText()) ) mongo_main_set_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("slave")) && (mElem->GetText()) ) mongo_main_slave_ok_ = strncmp(mElem->GetText(),"false", 5) > 0 ? false : true; if( (mElem = mel->FirstChildElement("login")) && (mElem->GetText()) ) mongo_main_login_ = mElem->GetText(); if( (mElem = mel->FirstChildElement("passwd")) && (mElem->GetText()) ) mongo_main_passwd_ = mElem->GetText(); } else { exit("no main section in mongo in config file. exit"); } } else { exit("no mongo section in config file. exit"); } if( (mElem = mRoot->FirstChildElement("log")) ) { if( (mel = mElem->FirstChildElement("coretime")) && (mel->GetText()) ) { logCoretime = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("key")) && (mel->GetText()) ) { logKey = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("country")) && (mel->GetText()) ) { logCountry = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("region")) && (mel->GetText()) ) { logRegion = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("context")) && (mel->GetText()) ) { logContext = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("search")) && (mel->GetText()) ) { logSearch = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("accountId")) && (mel->GetText()) ) { logAccountId = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } if( (mel = mElem->FirstChildElement("OutPutOfferIds")) && (mel->GetText()) ) { logOutPutOfferIds = strncmp(mel->GetText(),"1",1)>=0 ? true : false; } } else { logCoretime = logKey = logCountry = logRegion = logContext = logSearch = logAccountId = logOutPutOfferIds = false; } delete mDoc; mIsInited = true; std::clog<<"config file loaded"<<std::endl; return mIsInited; }
bool wxsProject::RecoverWxsFile( const wxString& ResourceDescription ) { TiXmlDocument doc; doc.Parse( ( _T("<") + ResourceDescription + _T(" />") ).mb_str( wxConvUTF8 ) ); if ( doc.Error() ) { wxMessageBox( cbC2U( doc.ErrorDesc() ) + wxString::Format(_T(" in %d x %d"), doc.ErrorRow(), doc.ErrorCol() ) ); return false; } TiXmlElement* elem = doc.RootElement(); if ( !elem ) { return false; } // Try to build resource of given type wxString Type = cbC2U(elem->Value()); wxsResource* Res = wxsResourceFactory::Build(Type,this); if ( !Res ) return false; // Read settings if ( !Res->ReadConfig( elem ) ) { delete Res; return false; } // Prevent duplicating resource names if ( FindResource( Res->GetResourceName() ) ) { delete Res; return false; } // Finally add the resource m_Resources.Add(Res); Res->BuildTreeEntry(GetResourceTypeTreeId(Type)); return true; }
//================================================================================================ // // Load() // // - Called by Main_OnInitDialog() // /// <summary> /// Attempts to load the config-file. Returns true if successful, false if not /// </summary> /// <remarks> /// If we're unsuccessful, the caller will assume this is the first time we've run the program /// and will run through the startup-wizard. /// </remarks> // bool Configuration::Load() { TRACEI("[Configuration] [Load] > Entering routine."); TiXmlDocument doc; const path pb=path::base_dir()/_T("peerblock.conf"); const path oldpb=path::base_dir()/_T("peerblock.conf.bak"); const path pg2=path::base_dir()/_T("pg2.conf"); vector<path> files; files.push_back(pb); files.push_back(oldpb); files.push_back(pg2); bool loaded = false; bool isDirty = false; for(vector<path>::iterator itr = files.begin(); itr != files.end() && !loaded; ++itr) { { HANDLE fp = NULL; HANDLE map = NULL; const void *view = NULL; if (!LoadFile((*itr).file_str().c_str(), &fp, &map, &view)) // first try to find a PeerBlock file { tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] WARNING: Unable to load configuration file [%1%]")) % (*itr).file_str().c_str() ); TRACEBUFW(strBuf); continue; } tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] Loaded configuration file [%1%]")) % (*itr).file_str().c_str() ); TRACEBUFI(strBuf); boost::shared_ptr<void> fp_safe(fp, CloseHandle); boost::shared_ptr<void> map_safe(map, CloseHandle); boost::shared_ptr<const void> view_safe(view, UnmapViewOfFile); doc.Parse((const char*)view); if(doc.Error()) { TRACEE("[Configuration] [Load] * ERROR: Can't parse xml document"); tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] * - Error: [%1%] (\"%2%\") at row:[%3%] col:[%4%]")) % doc.ErrorId() % doc.ErrorDesc() % doc.ErrorRow() % doc.ErrorCol() ); TRACEBUFE(strBuf); // copy over to .failed path failedFile; failedFile = itr->file_str(); failedFile = failedFile.file_str() + L".failed"; path::copy(*itr, failedFile, true); strBuf = boost::str(tformat(_T("[Configuration] [Load] - Copied failed-parsing config-file to: [%1%]")) % failedFile.file_str() ); TRACEBUFE(strBuf); continue; } } if (*itr == pb) { TRACEI("[Configuration] [Load] found peerblock configuration file"); } else if (*itr == oldpb) { TRACEW("[Configuration] [Load] using last-known-good configuration file"); MessageBox(NULL, IDS_CONFERRTEXT, IDS_CONFERR, MB_ICONWARNING|MB_OK); g_config.Save(_T("peerblock.conf")); // save restored config to regular file } else if (*itr == pg2) { TRACEI("[Configuration] [Load] found old-style pg2 configuration file"); } else // can't find anything, return false so caller can run the startup-wizard { TRACEW("[Configuration] [Load] WARNING: No configuration file found."); return false; } loaded = true; } if (!loaded) { // can't find anything, return false so caller can run the startup-wizard TRACEW("[Configuration] [Load] ERROR: No configuration file loaded!"); return false; } TRACEI("[Configuration] [Load] parsing config root element"); const TiXmlElement *root=doc.RootElement(); if(!root || (strcmp(root->Value(), "PeerGuardian2") && strcmp(root->Value(), "PeerBlock"))) { TRACEI("[Configuration] [Load] ERROR: Not a valid configuration file!"); return false; } TRACEI("[Configuration] [Load] parsing config settings element"); if(const TiXmlElement *settings=root->FirstChildElement("Settings")) { GetChild(settings, "Block", this->Block); if (GetChild(settings, "BlockHttp", this->PortSet.AllowHttp)) this->PortSet.AllowHttp = !this->PortSet.AllowHttp; GetChild(settings, "AllowLocal", this->AllowLocal); GetChild(settings, "CacheCrc", this->CacheCrc); GetChild(settings, "BlinkOnBlock", this->BlinkOnBlock); GetChild(settings, "NotifyOnBlock", this->NotifyOnBlock); GetChild(settings, "LastVersionRun", this->LastVersionRun); // specially-treat RecentBlockWarntime since otherwise TinyXML will save it to the .conf as a hex value int i=(DWORD)RecentBlockWarntime; GetChild(settings, "RecentBlockWarntime", i); this->RecentBlockWarntime=(DWORD)i; GetChild(settings, "ListSanityChecking", this->EnableListSanityChecking); GetChild(settings, "WarningIconForHttpAllow", this->EnableWarningIconForHttpAllow); } TRACEI("[Configuration] [Load] parsing config logging element"); if(const TiXmlElement *logging=root->FirstChildElement("Logging")) { GetChild(logging, "LogSize", this->LogSize); GetChild(logging, "LogAllowed", this->LogAllowed); GetChild(logging, "LogBlocked", this->LogBlocked); GetChild(logging, "ShowAllowed", this->ShowAllowed); GetChild(logging, "Cleanup", this->CleanupType); if(const TiXmlElement *c=logging->FirstChildElement("Cleanup")) { int i=0; if(c->Attribute("Interval", &i)) this->CleanupInterval=(unsigned short)i; } tstring p; if(GetChild(logging, "ArchivePath", p)) this->ArchivePath=p; GetChild(logging, "MaxHistorySize", this->MaxHistorySize); GetChild(logging, "HistoryCheckInterval", this->HistoryCheckInterval); } TRACEI("[Configuration] [Load] parsing config tracelogging element"); if(const TiXmlElement *logging=root->FirstChildElement("TraceLog")) { GetChild(logging, "Enabled", this->TracelogEnabled); GetChild(logging, "Level", this->TracelogLevel); } TRACEI("[Configuration] [Load] parsing config colors element"); if(const TiXmlElement *colors=root->FirstChildElement("Colors")) { GetChild(colors, "ColorCode", this->ColorCode); GetChild(colors, "Blocked", this->BlockedColor); GetChild(colors, "Allowed", this->AllowedColor); GetChild(colors, "Http", this->HttpColor); } TRACEI("[Configuration] [Load] parsing config windowing element"); if(const TiXmlElement *windowing=root->FirstChildElement("Windowing")) { GetChild(windowing, "Main", this->WindowPos); GetChild(windowing, "Update", this->UpdateWindowPos); GetChild(windowing, "ListManager", this->ListManagerWindowPos); GetChild(windowing, "ListEditor", this->ListEditorWindowPos); GetChild(windowing, "History", this->HistoryWindowPos); GetChild(windowing, "StartMinimized", this->StartMinimized); GetChild(windowing, "ShowSplash", this->ShowSplash); GetChild(windowing, "StayHidden", this->StayHidden); GetChild(windowing, "HideOnClose", this->HideOnClose); GetChild(windowing, "HideMain", this->WindowHidden); GetChild(windowing, "AlwaysOnTop", this->AlwaysOnTop); GetChild(windowing, "HideTrayIcon", this->HideTrayIcon); if(const TiXmlElement *hcol=windowing->FirstChildElement("HistoryColumns")) { int cols[6]= {0}; GetChild(hcol, "Time", cols[0]); GetChild(hcol, "Range", cols[1]); GetChild(hcol, "Source", cols[2]); GetChild(hcol, "Destination", cols[3]); GetChild(hcol, "Protocol", cols[4]); GetChild(hcol, "Action", cols[5]); SaveListColumns(cols, this->HistoryColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("LogColumns")) { int cols[6]= {0}; GetChild(lcol, "Time", cols[0]); GetChild(lcol, "Range", cols[1]); GetChild(lcol, "Source", cols[2]); GetChild(lcol, "Destination", cols[3]); GetChild(lcol, "Protocol", cols[4]); GetChild(lcol, "Action", cols[5]); SaveListColumns(cols, this->LogColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("ListEditorColumns")) { int cols[3]= {0}; GetChild(lcol, "Range", cols[0]); GetChild(lcol, "StartingIp", cols[1]); GetChild(lcol, "EndingIp", cols[2]); SaveListColumns(cols, this->ListEditorColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("ListManagerColumns")) { int cols[3]= {0}; GetChild(lcol, "File", cols[0]); GetChild(lcol, "Type", cols[1]); GetChild(lcol, "Description", cols[2]); SaveListColumns(cols, this->ListManagerColumns); } if(const TiXmlElement *ucol=windowing->FirstChildElement("UpdateColumns")) { int cols[3]= {0}; GetChild(ucol, "Description", cols[0]); GetChild(ucol, "Task", cols[1]); GetChild(ucol, "Status", cols[2]); SaveListColumns(cols, this->UpdateColumns); } } TRACEI("[Configuration] [Load] parsing config updates element"); if(const TiXmlElement *updates=root->FirstChildElement("Updates")) { string lastupdate; GetChild(updates, "UpdatePeerBlock", this->UpdatePeerBlock); GetChild(updates, "UpdateLists", this->UpdateLists); GetChild(updates, "UpdateAtStartup", this->UpdateAtStartup); GetChild(updates, "UpdateInterval", this->UpdateInterval); GetChild(updates, "UpdateCountdown", this->UpdateCountdown); GetChild(updates, "IgnoreListUpdateLimit", this->IgnoreListUpdateLimit); GetChild(updates, "UpdateProxy", this->UpdateProxy); if(const TiXmlElement *proxy=updates->FirstChildElement("UpdateProxy")) { const char *t=proxy->Attribute("Type"); this->UpdateProxyType=(t!=NULL && !strcmp(t, "http"))?CURLPROXY_HTTP:CURLPROXY_SOCKS5; } GetChild(updates, "LastUpdate", lastupdate); if(lastupdate.length()>0) { try { this->LastUpdate=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "LastArchived", lastupdate); if(lastupdate.length()>0) { try { this->LastArchived=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "LastStarted", lastupdate); if(lastupdate.length()>0) { try { this->LastStarted=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "UniqueId", UniqueId); if (EnsureUniqueId()) { // we generated a new unique ID for this, so make sure we save it later on isDirty = true; } } TRACEI("[Configuration] [Load] parsing config messages element"); if(const TiXmlElement *messages=root->FirstChildElement("Messages")) { GetChild(messages, "FirstBlock", this->FirstBlock); GetChild(messages, "FirstHide", this->FirstHide); } TRACEI("[Configuration] [Load] parsing config ports element"); if (const TiXmlElement *portset = root->FirstChildElement("PortSet")) { GetChild(portset, "AllowHttp", this->PortSet.AllowHttp); GetChild(portset, "AllowFtp", this->PortSet.AllowFtp); GetChild(portset, "AllowSmtp", this->PortSet.AllowSmtp); GetChild(portset, "AllowPop3", this->PortSet.AllowPop3); if (const TiXmlElement *profiles = portset->FirstChildElement("Profiles")) { for (const TiXmlElement *profile = profiles->FirstChildElement("Profile"); profile != NULL; profile = profile->NextSiblingElement("Profile")) { PortProfile pf; GetChild(profile, "Name", pf.Name); GetChild(profile, "Enabled", pf.Enabled); GetChild(profile, "Type", pf.Type); if (const TiXmlElement *ports = profile->FirstChildElement("Ports")) { for (const TiXmlElement *range = ports->FirstChildElement("Range"); range != NULL; range = range->NextSiblingElement("Range")) { const char *start = range->Attribute("Start"); const char *end = range->Attribute("End"); if (start) { try { USHORT s = boost::lexical_cast<USHORT>(start); USHORT e = s; if (end) e = boost::lexical_cast<USHORT>(end); PortRange pr; pr.Start = s; pr.End = e; pf.Ports.push_back(pr); } catch (boost::bad_lexical_cast &) { // not valid number } } } } this->PortSet.Profiles.push_back(pf); } } } TRACEI("[Configuration] [Load] parsing config lists element"); if(const TiXmlElement *lists=root->FirstChildElement("Lists")) { for(const TiXmlElement *list=lists->FirstChildElement("List"); list!=NULL; list=list->NextSiblingElement("List")) { string file, url, type, description, lastupdate, lastdownload; bool enabled, failedupdate=false; GetChild(list, "File", file); GetChild(list, "Url", url); GetChild(list, "Type", type); GetChild(list, "Description", description); GetChild(list, "LastUpdate", lastupdate); GetChild(list, "LastDownload", lastdownload); GetChild(list, "FailedUpdate", failedupdate); if(!GetChild(list, "Enabled", enabled)) enabled=true; if(file.length()>0) { StaticList l; l.Type=(type=="allow")?List::Allow:List::Block; l.File=UTF8_TSTRING(file); l.Description=UTF8_TSTRING(description); l.Enabled=enabled; this->StaticLists.push_back(l); } else { DynamicList l; l.Type=(type=="allow")?List::Allow:List::Block; l.Url=UTF8_TSTRING(url); l.Description=UTF8_TSTRING(description); l.Enabled=enabled; l.FailedUpdate=failedupdate; if(lastupdate.length()>0) { try { l.LastUpdate=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } if(lastdownload.length()>0) { try { l.LastDownload=boost::lexical_cast<int>(lastdownload); } catch(...) { // keep going } } this->DynamicLists.push_back(l); } } } TRACEI("[Configuration] [Load] parsing I-Blocklist Subscription element"); if(const TiXmlElement *ibl=root->FirstChildElement("I-Blocklist")) { GetChild(ibl, "Username", this->IblUsername); GetChild(ibl, "PIN", this->IblPin); } if (isDirty) { TRACEI("[Configuration] [Load] config loaded dirty, saving"); Save(); } TRACEI("[Configuration] [Load] < Leaving routine."); return true; } // End of Load()
bool CGUIIncludes::LoadIncludes(const CStdString &includeFile) { // check to see if we already have this loaded if (HasIncludeFile(includeFile)) return true; TiXmlDocument doc; if (!doc.LoadFile(includeFile)) { CLog::Log(LOGINFO, "Error loading includes.xml file (%s): %s (row=%i, col=%i)", includeFile.c_str(), doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol()); return false; } // success, load the tags if (LoadIncludesFromXML(doc.RootElement())) { m_files.push_back(includeFile); return true; } return false; }
void CAppRegistry::Load(const CAppDescriptor& desc, bool persistent) { CSingleLock lock(m_lock); m_data.clear(); if (!persistent) { m_dir = _P(g_settings.GetProfileUserDataFolder()); CUtil::AddFileToFolder(m_dir, "apps", m_dir); ::CreateDirectory(m_dir, NULL); CUtil::AddFileToFolder(m_dir, desc.GetId(), m_dir); ::CreateDirectory(m_dir, NULL); } else { m_dir = "/.persistent"; CUtil::AddFileToFolder(m_dir, "apps", m_dir); ::CreateDirectory(m_dir, NULL); CUtil::AddFileToFolder(m_dir, desc.GetId(), m_dir); ::CreateDirectory(m_dir, NULL); } m_fileName = m_dir; CUtil::AddFileToFolder(m_fileName, "registry.xml", m_fileName); // Registry was not found. Silently return. if (!XFILE::CFile::Exists(m_fileName)) { return; } TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(m_fileName)) { CLog::Log(LOGERROR, "Cannot load descriptor file for app: %s at row=%d/col=%d", xmlDoc.ErrorDesc(), xmlDoc.ErrorRow(), xmlDoc.ErrorCol()); return; } TiXmlElement* rootElement = xmlDoc.RootElement(); if (strcmpi(rootElement->Value(), "registry") != 0) { CLog::Log(LOGERROR, "Invalid registry file, root element should be registry: %s", m_fileName.c_str()); return; } const TiXmlElement *node = rootElement->FirstChildElement("value"); while (node) { const char* keyStr = node->Attribute("id"); if (!keyStr) { CLog::Log(LOGWARNING, "Attribute id missing for element: %s", m_fileName.c_str()); continue; } const char* valueStr = node->GetText(); CStdString key = keyStr; CStdString value = ""; if (valueStr) { value = valueStr; } if (m_data.find(key) == m_data.end()) { RegistryValue values; m_data[key] = values; } RegistryValue& values = m_data[key]; values.push_back(value); node = node->NextSiblingElement("value"); } }
bool ISNorm::LoadParams(const ssi_char_t *path, Params ¶ms) { FilePath fp(path); ssi_char_t *path_xml; ssi_char_t *path_data; if (ssi_strcmp(fp.getExtension(), ".norm", false)) { path_xml = ssi_strcpy(path); } else { path_xml = ssi_strcat(path, ".norm"); } path_data = ssi_strcat(path_xml, "~"); TiXmlDocument doc; if (!doc.LoadFile(path_xml)) { ssi_wrn("failed loading trainer from file '%s' (r:%d,c:%d)", path_xml, doc.ErrorRow(), doc.ErrorCol()); return false; } TiXmlElement *body = doc.FirstChildElement(); if (!body || strcmp(body->Value(), "norm") != 0) { ssi_wrn("tag <norm> missing"); return false; } TiXmlElement *element = 0; element = body->FirstChildElement("method"); const ssi_char_t *method_s = element->GetText(); bool found = false; METHOD::List method; for (ssi_size_t i = 0; i < METHOD::NUM; i++) { if (ssi_strcmp(method_s, METHOD_NAMES[i], false)) { method = (METHOD::List) i; found = true; } } if (!found) { ssi_wrn("unkown method '%s'", method_s); return false; } ISNorm::ZeroParams(params, method); element = body->FirstChildElement("dim"); const ssi_char_t *dim_s = element->GetText(); ssi_size_t dim; if (sscanf(dim_s, "%u", &dim) != 1) { ssi_wrn("could not parse dimension '%s'", dim_s); return false; } ISNorm::InitParams(params, dim); if (method == METHOD::SCALE) { element = body->FirstChildElement("limits"); const ssi_char_t *limits_s = element->GetText(); if (sscanf(limits_s, "%f %f", params.limits, params.limits + 1) != 2) { ssi_wrn("could not parse limits '%s'", limits_s); return false; } } element = body->FirstChildElement("type"); const ssi_char_t *type_s = element->GetText(); found = false; File::TYPE type; if (ssi_strcmp(type_s, File::TYPE_NAMES[File::ASCII], false)) { type = File::ASCII; found = true; } else if (ssi_strcmp(type_s, File::TYPE_NAMES[File::BINARY], false)) { type = File::BINARY; found = true; } if (!found) { ssi_wrn("unkown type '%s'", type_s); return false; } if (method != METHOD::NONE) { FILE *fp = fopen(path_data, type == File::BINARY ? "rb" : "r"); if (fp) { switch (params.method) { case METHOD::NONE: break; case METHOD::SCALE: if (type == File::BINARY) { fread(params.mins, params.n_features, sizeof(ssi_real_t), fp); fread(params.maxs, params.n_features, sizeof(ssi_real_t), fp); } else { ssi_real_t *mins = params.mins; ssi_real_t *maxs = params.maxs; for (ssi_size_t i = 0; i < params.n_features; i++) { fscanf(fp, "%f %f\n", mins++, maxs++); } } break; case METHOD::ZSCORE: if (type == File::BINARY) { fread(params.mean, params.n_features, sizeof(ssi_real_t), fp); fread(params.stdv, params.n_features, sizeof(ssi_real_t), fp); } else { ssi_real_t *mean = params.mean; ssi_real_t *stdv = params.stdv; for (ssi_size_t i = 0; i < params.n_features; i++) { fscanf(fp, "%f %f\n", mean++, stdv++); } } break; } fclose(fp); } else { ssi_wrn("could not open file '%s'", path_data); return false; } } delete[] path_xml; delete[] path_data; return true; }
bool JUnitOutputter::write(std::string filename, RTF::TestMessage* errorMsg) { if(filename.empty()) { if(errorMsg != nullptr) { errorMsg->setMessage("Cannot open the file."); errorMsg->setDetail("Empty file name."); } return false; } TiXmlDocument doc; TiXmlElement* root = new TiXmlElement("testsuites"); root->SetAttribute("suites", collector.suiteCount()); root->SetAttribute("tests", collector.testCount()); root->SetAttribute("failures", collector.failedCount()); doc.LinkEndChild(root); TiXmlElement* testsuite = nullptr; TiXmlElement* testcase = nullptr; string classname; // If there is not any test suite, add one! if(collector.suiteCount() == 0) { classname = "default"; testsuite = new TiXmlElement("testsuite"); testsuite->SetAttribute("name", classname.c_str()); root->LinkEndChild(testsuite); } TestResultCollector::EventResultIterator itr; TestResultCollector::EventResultContainer events = collector.getResults(); string errorMessages, failureMessages, reportsMessages; for(itr=events.begin(); itr!=events.end(); ++itr) { ResultEvent* e = *itr; // start suit if(dynamic_cast<ResultEventStartSuite*>(e)) { classname = e->getTest()->getName(); testsuite = new TiXmlElement("testsuite"); testsuite->SetAttribute("name", classname.c_str()); root->LinkEndChild(testsuite); } // end suit //else if(dynamic_cast<ResultEventEndSuite*>(e)) { } // start test case else if(dynamic_cast<ResultEventStartTest*>(e)) { if(testsuite == nullptr) continue; testcase = new TiXmlElement("testcase"); testcase->SetAttribute("name", e->getTest()->getName()); testcase->SetAttribute("classname", classname+"."+e->getTest()->getName()); testsuite->LinkEndChild(testcase); errorMessages.clear(); failureMessages.clear(); reportsMessages.clear(); } // end test case else if(dynamic_cast<ResultEventEndTest*>(e)) { if(testcase == nullptr) continue; // adding falures if(failureMessages.size()) { TiXmlElement * failure = new TiXmlElement("failure"); failure->SetAttribute("message", "Something went wrong. See Stacktrace for detail."); failure->LinkEndChild(new TiXmlText(failureMessages.c_str())); testcase->LinkEndChild(failure); } // adding errors if(errorMessages.size()){ TiXmlElement * error = new TiXmlElement("error"); error->SetAttribute("message", "Something went wrong. See Stacktrace for detail."); error->LinkEndChild(new TiXmlText(errorMessages.c_str())); testcase->LinkEndChild(error); } // adding reports if(reportsMessages.size()) { TiXmlElement * report = new TiXmlElement("system-out"); report->SetAttribute("message", "See Standard Output for detail."); report->LinkEndChild(new TiXmlText(reportsMessages.c_str())); testcase->LinkEndChild(report); } } // failure event else if(dynamic_cast<ResultEventFailure*>(e)) { string msg; if(verbose) { msg = Asserter::format("%s : %s (%s at %d) <br>", e->getMessage().getMessage().c_str(), e->getMessage().getDetail().c_str(), e->getMessage().getSourceFileName().c_str(), e->getMessage().getSourceLineNumber()); } else msg = e->getMessage().getMessage() + ": " + e->getMessage().getDetail() + "\n"; failureMessages += msg; reportsMessages += MSG_FAIL + e->getTest()->getName()+ ") " + msg; } // error event else if(dynamic_cast<ResultEventError*>(e)) { string msg; if(verbose) { msg = Asserter::format("%s : %s (%s at %d) <br>", e->getMessage().getMessage().c_str(), e->getMessage().getDetail().c_str(), e->getMessage().getSourceFileName().c_str(), e->getMessage().getSourceLineNumber()); } else msg = e->getMessage().getMessage() + ": " + e->getMessage().getDetail() + "\n"; errorMessages += msg; reportsMessages += MSG_ERROR + e->getTest()->getName()+ ") " + msg; } // report event else if(dynamic_cast<ResultEventReport*>(e)) { string msg; if(verbose) { msg = Asserter::format("%s : %s (%s at %d) <br>", e->getMessage().getMessage().c_str(), e->getMessage().getDetail().c_str(), e->getMessage().getSourceFileName().c_str(), e->getMessage().getSourceLineNumber()); } else msg = e->getMessage().getMessage() + ": " + e->getMessage().getDetail() + "\n"; reportsMessages += MSG_REPORT + e->getTest()->getName()+ ") " + msg; } } // end for if(!doc.SaveFile(filename.c_str())) { if(errorMsg != nullptr) { errorMsg->setMessage("Cannot write to the " + filename); if (doc.Error()) errorMsg->setDetail(Asserter::format("%s (line: %d, column %d)", doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol())); } return false; } return true; }
std::vector<itk::SmartPointer<mitk::BaseData>> mitk::PointSetReaderService::Read() { // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); std::vector<itk::SmartPointer<mitk::BaseData>> result; InputStream stream(this); TiXmlDocument doc; stream >> doc; if (!doc.Error()) { TiXmlHandle docHandle(&doc); // unsigned int pointSetCounter(0); for (TiXmlElement *currentPointSetElement = docHandle.FirstChildElement("point_set_file").FirstChildElement("point_set").ToElement(); currentPointSetElement != NULL; currentPointSetElement = currentPointSetElement->NextSiblingElement()) { mitk::PointSet::Pointer newPointSet = mitk::PointSet::New(); // time geometry assembled for addition after all points // else the SetPoint method would already transform the points that we provide it mitk::ProportionalTimeGeometry::Pointer timeGeometry = mitk::ProportionalTimeGeometry::New(); if (currentPointSetElement->FirstChildElement("time_series") != NULL) { for (TiXmlElement *currentTimeSeries = currentPointSetElement->FirstChildElement("time_series")->ToElement(); currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement()) { unsigned int currentTimeStep(0); TiXmlElement *currentTimeSeriesID = currentTimeSeries->FirstChildElement("time_series_id"); currentTimeStep = atoi(currentTimeSeriesID->GetText()); timeGeometry->Expand(currentTimeStep + 1); // expand (default to identity) in any case TiXmlElement *geometryElem = currentTimeSeries->FirstChildElement("Geometry3D"); if (geometryElem) { Geometry3D::Pointer geometry = Geometry3DToXML::FromXML(geometryElem); if (geometry.IsNotNull()) { timeGeometry->SetTimeStepGeometry(geometry, currentTimeStep); } else { MITK_ERROR << "Could not deserialize Geometry3D element."; } } else { MITK_WARN << "Fallback to legacy behavior: defining PointSet geometry as identity"; } newPointSet = this->ReadPoints(newPointSet, currentTimeSeries, currentTimeStep); } } else { newPointSet = this->ReadPoints(newPointSet, currentPointSetElement, 0); } newPointSet->SetTimeGeometry(timeGeometry); result.push_back(newPointSet.GetPointer()); } } else { mitkThrow() << "Parsing error at line " << doc.ErrorRow() << ", col " << doc.ErrorCol() << ": " << doc.ErrorDesc(); } return result; }
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 ) QueryPerformanceCounter( (LARGE_INTEGER*) (&start) ); #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" ); doc.Print( stdout ); 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 Dinosours!" 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(); 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 sytax. 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 doc; doc.Parse( error ); XmlTest( "Error row", doc.ErrorRow(), 3 ); XmlTest( "Error column", doc.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } { 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 ); } { 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 = "<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 ); } #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 // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "utf8testout.xml", "r" ); FILE* verify = fopen( "utf8testverify.xml", "r" ); if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); if ( strcmp( verifyBuf, savedBuf ) ) { okay = 0; break; } } fclose( saved ); fclose( verify ); } XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else comletely 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.", 0, (int) 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 ////////////////////////////////////////////////////// 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 // verifing 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.", 0, (int)doc.Error() ); // not an error to tinyxml XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<ä>" "CöntäntßäöüÄÖÜ" "</ä>"; TiXmlDocument doc; doc.Parse( str ); //doc.Print( stdout, 0 ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() ); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif #if defined( WIN32 ) && defined( TUNE ) QueryPerformanceCounter( (LARGE_INTEGER*) (&end) ); QueryPerformanceFrequency( (LARGE_INTEGER*) (&freq) ); printf( "Time for run: %f\n", ( double )( end-start ) / (double) freq ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
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; }
CDLTransformRcPtr CDLTransform::CreateFromFile(const char * src, const char * cccid) { if(!src || (strlen(src) == 0) || !cccid) { std::ostringstream os; os << "Error loading CDL xml. "; os << "Source file not specified."; throw Exception(os.str().c_str()); } // Check cache AutoMutex lock(g_cacheMutex); { CDLTransformMap::iterator iter = g_cache.find(GetCDLLocalCacheKey(src,cccid)); if(iter != g_cache.end()) { return iter->second; } } std::ifstream istream(src); if(istream.fail()) { std::ostringstream os; os << "Error could not read CDL source file '" << src; os << "'. Please verify the file exists and appropriate "; os << "permissions are set."; throw Exception (os.str().c_str()); } // Read the file into a string. std::ostringstream rawdata; rawdata << istream.rdbuf(); std::string xml = rawdata.str(); if(xml.empty()) { std::ostringstream os; os << "Error loading CDL xml. "; os << "The specified source file, '"; os << src << "' appears to be empty."; throw Exception(os.str().c_str()); } TiXmlDocument doc; doc.Parse(xml.c_str()); if(doc.Error()) { std::ostringstream os; os << "Error loading CDL xml from file '"; os << src << "'. "; os << doc.ErrorDesc() << " (line "; os << doc.ErrorRow() << ", character "; os << doc.ErrorCol() << ")"; throw Exception(os.str().c_str()); } if(!doc.RootElement()) { std::ostringstream os; os << "Error loading CDL xml from file '"; os << src << "'. "; os << "Please confirm the xml is valid."; throw Exception(os.str().c_str()); } std::string rootValue = doc.RootElement()->Value(); if(rootValue == "ColorCorrection") { // Load a single ColorCorrection into the cache CDLTransformRcPtr cdl = CDLTransform::Create(); LoadCDL(cdl.get(), doc.RootElement()->ToElement()); g_cache[GetCDLLocalCacheKey(src,cccid)] = cdl; return cdl; } else if(rootValue == "ColorCorrectionCollection") { // Load all CCs from the ColorCorrectionCollection // into the cache CDLTransformMap transforms; GetCDLTransforms(transforms, doc.RootElement()); if(transforms.empty()) { std::ostringstream os; os << "Error loading ccc xml. "; os << "No ColorCorrection elements found in file '"; os << src << "'."; throw Exception(os.str().c_str()); } for(CDLTransformMap::iterator iter = transforms.begin(); iter != transforms.end(); ++iter) { g_cache[GetCDLLocalCacheKey(src,iter->first)] = iter->second; } CDLTransformMap::iterator cciter = g_cache.find(GetCDLLocalCacheKey(src,cccid)); if(cciter == g_cache.end()) { std::ostringstream os; os << "Error loading ccc xml. "; os << "The specified cccid " << cccid << " "; os << "could not be found in file '"; os << src << "'."; throw Exception(os.str().c_str()); } return cciter->second; } std::ostringstream os; os << "Error loading CDL xml from file '"; os << src << "'. "; os << "Root xml element is type '" << rootValue << "', "; os << "ColorCorrection or ColorCorrectionCollection expected."; throw Exception(os.str().c_str()); }
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öntäntßäöüÄÖÜ" "</ä>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() ); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // Bug [ 1195696 ] from marlonism TiXmlBase::SetCondenseWhiteSpace(false); TiXmlDocument xml; xml.Parse("<text><break/>This hangs</text>"); XmlTest( "Test safe error return.", xml.Error(), false ); } { // Bug [ 1243992 ] - another infinite loop TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); doc.Parse("<p><pb></pb>test</p>"); } { // Low entities TiXmlDocument xml; xml.Parse( "<test></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; }
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=\"Vo‚\" 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 ) QueryPerformanceCounter( (LARGE_INTEGER*) (&start) ); #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(); } ostringstream outputStream( ostringstream::out ); { 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" ); doc.Print( stdout ); 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 Dinosours!" 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", "Vo‚" ); 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"; outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), outputStream.str().c_str(), true ); #endif node = doc.RootElement(); 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 sytax. 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 doc; doc.Parse( error ); XmlTest( "Error row", doc.ErrorRow(), 3 ); XmlTest( "Error column", doc.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } { 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 ); } { 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 = "<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", static_cast<int>(dVal), 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", static_cast<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 ); } #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 ////////////////////////////////////////////////////// #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 ); #endif ////////////////////////////////////////////////////// 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 // verifing 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" ); doc.LoadFile(); // 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 ©.\"> </psg>" "</passages>"; TiXmlDocument doc( "passages.xml" ); doc.Parse( passages ); TiXmlElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); XmlTest( "Entity transformation: read. ", "Line 5 has \"quotation marks\" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake \xA9.", 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 ©.' />", 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" ); } } #if defined( WIN32 ) && defined( TUNE ) QueryPerformanceCounter( (LARGE_INTEGER*) (&end) ); QueryPerformanceFrequency( (LARGE_INTEGER*) (&freq) ); printf( "Time for run: %f\n", ( double )( end-start ) / (double) freq ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }