/* * Look for a "layout.xml" in the specified directory. If found, parse * the contents out. * * Returns "true" on success, "false" on failure. */ bool PhoneData::Create(const char* directory) { android::String8 fileName; SetDirectory(directory); fileName = directory; fileName += "/"; fileName += PhoneCollection::kLayoutFile; #ifdef BEFORE_ASSET TiXmlDocument doc(fileName); if (!doc.LoadFile()) #else android::AssetManager* pAssetMgr = ((MyApp*)wxTheApp)->GetAssetManager(); TiXmlDocument doc; android::Asset* pAsset; bool result; pAsset = pAssetMgr->open(fileName, Asset::ACCESS_STREAMING); if (pAsset == NULL) { fprintf(stderr, "Unable to open asset '%s'\n", (const char*) fileName); return false; } else { //printf("--- opened asset '%s'\n", // (const char*) pAsset->getAssetSource()); } /* TinyXml insists that the buffer be NULL-terminated... ugh */ char* buf = new char[pAsset->getLength() +1]; pAsset->read(buf, pAsset->getLength()); buf[pAsset->getLength()] = '\0'; delete pAsset; result = doc.Parse(buf); delete[] buf; if (!result) #endif { fprintf(stderr, "SimCFG: ERROR: failed parsing '%s'\n", (const char*) fileName); if (doc.ErrorRow() != 0) fprintf(stderr, " XML: %s (row=%d col=%d)\n", doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol()); else fprintf(stderr, " XML: %s\n", doc.ErrorDesc()); return false; } if (!ProcessAndValidate(&doc)) { fprintf(stderr, "SimCFG: ERROR: failed analyzing '%s'\n", (const char*) fileName); return false; } printf("SimCFG: loaded data from '%s'\n", (const char*) fileName); return true; }
XmlDocument* XmlDocument::load( std::istream& in, const URI& sourceURI ) { TiXmlDocument xmlDoc; //Read the entire document into a string std::stringstream buffer; buffer << in.rdbuf(); std::string xmlStr(buffer.str()); removeDocType( xmlStr ); //OE_NOTICE << xmlStr; XmlDocument* doc = NULL; xmlDoc.Parse(xmlStr.c_str()); if ( xmlDoc.Error() ) { std::stringstream buf; buf << xmlDoc.ErrorDesc() << " (row " << xmlDoc.ErrorRow() << ", col " << xmlDoc.ErrorCol() << ")"; std::string str = buf.str(); OE_WARN << "Error in XML document: " << str << std::endl; } if ( !xmlDoc.Error() && xmlDoc.RootElement() ) { doc = new XmlDocument(); processNode( doc, xmlDoc.RootElement() ); doc->_sourceURI = sourceURI; } return doc; }
void LoadCDL(CDLTransform * cdl, const char * xml) { if(!xml || (strlen(xml) == 0)) { std::ostringstream os; os << "Error loading CDL xml. "; os << "Null string provided."; throw Exception(os.str().c_str()); } TiXmlDocument doc; doc.Parse(xml); if(doc.Error()) { std::ostringstream os; os << "Error loading CDL xml. "; 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, "; os << "please confirm the xml is valid."; throw Exception(os.str().c_str()); } LoadCDL(cdl, doc.RootElement()->ToElement()); }
bool XMLHelper::Load(TiXmlDocument& xmlDoc, Ogre::DataStreamPtr stream) { size_t length(stream->size()); if ( length ) { // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. std::string data(stream->getAsString()); xmlDoc.Parse( data.c_str()); if (xmlDoc.Error() ) { std::string errorDesc = xmlDoc.ErrorDesc(); int errorLine = xmlDoc.ErrorRow(); int errorColumn = xmlDoc.ErrorCol(); std::stringstream ss; ss << "Failed to load xml file '" << stream->getName() << "'! Error at column: " << errorColumn << " line: " << errorLine << ". Error message: " << errorDesc; S_LOG_FAILURE(ss.str()); return false; } else { return true; } } return false; }
void CPasswordManager::Load() { Clear(); CStdString passwordsFile = g_settings.GetUserDataItem("passwords.xml"); if (XFILE::CFile::Exists(passwordsFile)) { TiXmlDocument doc; if (!doc.LoadFile(passwordsFile)) { CLog::Log(LOGERROR, "%s - Unable to load: %s, Line %d\n%s", __FUNCTION__, passwordsFile.c_str(), doc.ErrorRow(), doc.ErrorDesc()); return; } const TiXmlElement *root = doc.RootElement(); if (root->ValueStr() != "passwords") return; // read in our passwords const TiXmlElement *path = root->FirstChildElement("path"); while (path) { CStdString from, to; if (XMLUtils::GetPath(path, "from", from) && XMLUtils::GetPath(path, "to", to)) { m_permanentCache[from] = to; m_temporaryCache[from] = to; m_temporaryCache[GetServerLookup(from)] = to; } path = path->NextSiblingElement("path"); } } m_loaded = true; }
bool CompileJob::analyzeArticle() { if (Program::verbose) logs.info() << "reading " << pArticle.relativeFilename; // Article order { if (!extractOrder(pArticle.originalFilename)) pArticle.order = 1000u; if (Program::debug) logs.info() << " :: " << pArticle.relativeFilename << ", order = " << pArticle.order; } TiXmlDocument doc; if (!doc.LoadFile(pArticle.originalFilename.c_str(), TIXML_ENCODING_UTF8)) { logs.error() << pArticle.relativeFilename << ", l" << doc.ErrorRow() << ": " << doc.ErrorDesc(); return false; } // Analyze the XML document XMLVisitor visitor(pArticle, doc); if (!doc.Accept(&visitor) || visitor.error()) { pArticle.error = true; return false; } if (!pArticle.title) IO::ExtractFileName(pArticle.title, pArticle.htdocsFilename, false); // TOC refactoring pArticle.tocRefactoring(); return true; }
void XMLInputBase::injectIncludeFiles (TiXmlElement* tag) const { static int nLevels = 0; ++nLevels; bool foundIncludes = false; TiXmlElement* elem = tag->FirstChildElement(); for (; elem; elem = elem->NextSiblingElement()) if (strcasecmp(elem->Value(),"include")) this->injectIncludeFiles(elem); else if (elem->FirstChild() && elem->FirstChild()->Value()) { TiXmlDocument doc; if (doc.LoadFile(elem->FirstChild()->Value())) { for (int i = 1; i < nLevels; i++) IFEM::cout <<" "; IFEM::cout <<"Loaded included file "<< elem->FirstChild()->Value() << std::endl; elem = tag->ReplaceChild(elem,*doc.RootElement())->ToElement(); TiXmlElement* elem2 = doc.RootElement()->NextSiblingElement(); for (; elem2; elem2 = elem2->NextSiblingElement()) tag->LinkEndChild(new TiXmlElement(*elem2)); foundIncludes = true; } else std::cerr << __PRETTY_FUNCTION__ <<": Failed to load " << elem->FirstChild()->Value() <<"\n\tError at line "<< doc.ErrorRow() <<": " << doc.ErrorDesc() << std::endl; } if (foundIncludes) this->injectIncludeFiles(tag); --nLevels; }
RobotInterface::Robot& RobotInterface::XMLReader::Private::readRobotFile(const std::string &fileName) { filename = fileName; #ifdef WIN32 std::replace(filename.begin(), filename.end(), '/', '\\'); #endif curr_filename = fileName; #ifdef WIN32 path = filename.substr(0, filename.rfind("\\")); #else // WIN32 path = filename.substr(0, filename.rfind("/")); #endif //WIN32 yDebug() << "Reading file" << filename.c_str(); TiXmlDocument *doc = new TiXmlDocument(filename.c_str()); if (!doc->LoadFile()) { SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc(); } if (!doc->RootElement()) { SYNTAX_ERROR(doc->Row()) << "No root element."; } for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) { if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) { if(dtd.parse(childNode->ToUnknown(), curr_filename)) { break; } } } if (!dtd.valid()) { SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0"; dtd.setDefault(); dtd.type = RobotInterfaceDTD::DocTypeRobot; } if(dtd.type != RobotInterfaceDTD::DocTypeRobot) { SYNTAX_WARNING(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeRobot) << ". Found" << DocTypeToString(dtd.type); } if(dtd.majorVersion != 1 || dtd.minorVersion != 0) { SYNTAX_WARNING(doc->Row()) << "Only robotInterface DTD version 1.0 is supported"; } readRobotTag(doc->RootElement()); delete doc; // yDebug() << robot; return robot; }
bool CGUIWindow::LoadXML(const CStdString &strPath, const CStdString &strLowerPath) { TiXmlDocument xmlDoc; if ( !xmlDoc.LoadFile(strPath) && !xmlDoc.LoadFile(CStdString(strPath).ToLower()) && !xmlDoc.LoadFile(strLowerPath)) { CLog::Log(LOGERROR, "unable to load:%s, Line %d\n%s", strPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); SetID(WINDOW_INVALID); return false; } return Load(xmlDoc); }
bool CButtonTranslator::Load() { // load our xml file, and fill up our mapping tables TiXmlDocument xmlDoc; // Load the config file CStdString keymapPath; //CUtil::AddFileToFolder(g_settings.GetUserDataFolder(), "Keymap.xml", keymapPath); keymapPath = g_settings.GetUserDataItem("Keymap.xml"); CLog::Log(LOGINFO, "Loading %s", keymapPath.c_str()); if (!xmlDoc.LoadFile(keymapPath)) { g_LoadErrorStr.Format("%s, Line %d\n%s", keymapPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } translatorMap.clear(); TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if ( strValue != "keymap") { g_LoadErrorStr.Format("%sl Doesn't contain <keymap>", keymapPath.c_str()); return false; } // run through our window groups TiXmlNode* pWindow = pRoot->FirstChild(); while (pWindow) { WORD wWindowID = WINDOW_INVALID; const char *szWindow = pWindow->Value(); { if (szWindow) { if (strcmpi(szWindow, "global") == 0) wWindowID = (WORD) -1; else wWindowID = TranslateWindowString(szWindow); } MapWindowActions(pWindow, wWindowID); pWindow = pWindow->NextSibling(); } } #ifdef HAS_LIRC if (!LoadLircMap()) return false; #endif // Done! return true; }
XN_C_API XnStatus xnContextRunXmlScript(XnContext* pContext, const XnChar* xmlScript, XnEnumerationErrors* pErrors) { XnStatus nRetVal = XN_STATUS_OK; TiXmlDocument doc; if (!doc.Parse(xmlScript)) { XN_LOG_ERROR_RETURN(XN_STATUS_CORRUPT_FILE, XN_MASK_OPEN_NI, "Failed loading xml: %s [row %d, column %d]", doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol()); } return RunXmlScriptImpl(pContext, &doc, pErrors); }
bool CButtonTranslator::LoadLircMap(const CStdString &lircmapPath) { #ifdef _LINUX #define REMOTEMAPTAG "lircmap" #else #define REMOTEMAPTAG "irssmap" #endif // load our xml file, and fill up our mapping tables TiXmlDocument xmlDoc; // Load the config file CLog::Log(LOGINFO, "Loading %s", lircmapPath.c_str()); if (!xmlDoc.LoadFile(lircmapPath)) { CLog::Log(LOGERROR, "%s, Line %d\n%s", lircmapPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; // This is so people who don't have the file won't fail, just warn } TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if (strValue != REMOTEMAPTAG) { CLog::Log(LOGERROR, "%sl Doesn't contain <%s>", lircmapPath.c_str(), REMOTEMAPTAG); return false; } // run through our window groups TiXmlNode* pRemote = pRoot->FirstChild(); while (pRemote) { if (pRemote->Type() == TiXmlNode::ELEMENT) { const char *szRemote = pRemote->Value(); if (szRemote) { TiXmlAttribute* pAttr = pRemote->ToElement()->FirstAttribute(); const char* szDeviceName = pAttr->Value(); MapRemote(pRemote, szDeviceName); } } pRemote = pRemote->NextSibling(); } return true; }
RobotInterface::ActionList RobotInterface::XMLReader::Private::readActionsFile(const std::string &fileName) { std::string old_filename = curr_filename; curr_filename = fileName; yDebug() << "Reading file" << fileName.c_str(); TiXmlDocument *doc = new TiXmlDocument(fileName.c_str()); if (!doc->LoadFile()) { SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc(); } if (!doc->RootElement()) { SYNTAX_ERROR(doc->Row()) << "No root element."; } RobotInterfaceDTD actionsFileDTD; for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) { if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) { if(actionsFileDTD.parse(childNode->ToUnknown(), curr_filename)) { break; } } } if (!actionsFileDTD.valid()) { SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0"; actionsFileDTD.setDefault(); actionsFileDTD.type = RobotInterfaceDTD::DocTypeActions; } if (actionsFileDTD.type != RobotInterfaceDTD::DocTypeActions) { SYNTAX_ERROR(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeActions) << ". Found" << DocTypeToString(actionsFileDTD.type); } if (actionsFileDTD.majorVersion != dtd.majorVersion) { SYNTAX_ERROR(doc->Row()) << "Trying to import a file with a different robotInterface DTD version"; } RobotInterface::ActionList actions = readActionsTag(doc->RootElement()); delete doc; curr_filename = old_filename; return actions; }
bool XMLInputBase::readXML (const char* fileName, bool verbose) { TiXmlDocument doc; if (!doc.LoadFile(fileName)) { std::cerr << __PRETTY_FUNCTION__ <<": Failed to load "<< fileName <<"\n\tError at line "<< doc.ErrorRow() <<": " << doc.ErrorDesc() << std::endl; return false; } const TiXmlElement* tag = doc.RootElement(); if (!tag || strcmp(tag->Value(),"simulation")) { std::cerr << __PRETTY_FUNCTION__ <<": Malformatted input file "<< fileName << std::endl; return false; } if (verbose) IFEM::cout <<"\nParsing input file "<< fileName << std::endl; this->injectIncludeFiles(const_cast<TiXmlElement*>(tag)); std::vector<const TiXmlElement*> parsed; if (!handlePriorityTags(doc.RootElement(),parsed,verbose)) return false; for (tag = tag->FirstChildElement(); tag; tag = tag->NextSiblingElement()) if (std::find(parsed.begin(),parsed.end(),tag) == parsed.end()) { if (verbose) IFEM::cout <<"\nParsing <"<< tag->Value() <<">"<< std::endl; if (!this->parse(tag)) { std::cerr <<" *** SIMinput::read: Failure occured while parsing \"" << tag->Value() <<"\""<< std::endl; return false; } } if (verbose) IFEM::cout <<"\nParsing input file succeeded."<< std::endl; return true; }
void Plasm::convertOldXml(char* infilename,char* outfilename,char* prefix) { ::prefix=std::string(prefix); TiXmlDocument doc; unsigned long filesize; unsigned char* buff=FileSystem::ReadFile(infilename,filesize,true); if (!doc.Parse((const char*)buff)) { MemPool::getSingleton()->free(filesize,buff); Utils::Error(HERE,"Failed to open XML fle %s [%d] %s",infilename,doc.ErrorRow(),doc.ErrorDesc()); } MemPool::getSingleton()->free(filesize,buff); TiXmlNode* xnode=doc.FirstChild(); const char* xname=xnode->Value(); XgeReleaseAssert(!strcmpi(xname,"mesh")); //geometry std::map<int, SmartPointer<Vector > > arrays; TiXmlNode* xgeometry=getChild(xnode,"arrays"); for (TiXmlNode* xchild= xgeometry->FirstChild(); xchild != 0; xchild = xchild->NextSibling()) { XgeReleaseAssert(!strcmpi(xchild->Value(),"array")); int id =atoi(getAttribute(xchild,"id" )->Value()); int size =atoi(getAttribute(xchild,"size")->Value()); SmartPointer<Vector> arr(new Vector(size)); Vector::parse(size,arr->mem(),xchild->FirstChild()->Value(),(char*)"%e"); arrays[id]=arr; } SmartPointer<Hpc> hpc=openXmlNode(getChild(xnode,"node"),arrays); Log::printf("Opened XML file %s\n",infilename); Plasm::save(hpc,outfilename); }
void make_solution_for_ub( project_info_table& info ) { TiXmlDocument root; std::string path = util::string::wc2mb( info.project_file_path.c_str() ); root.LoadFile( path.c_str() ); std::string backup_path = path + "_backup"; root.SaveFile( backup_path.c_str() ); if ( root.Error() == true ) { printf( "loading error file : %s errorID : %d , errorRow : %d errorCol : %d" , path.c_str() , root.ErrorId() , root.ErrorRow() , root.ErrorCol() ); return; } TiXmlNode* pRoot = root.FirstChildElement("Project"); if ( pRoot == NULL ) return; TiXmlNode* pItemGroup = pRoot->FirstChild("ItemGroup"); if ( pItemGroup == NULL ) return; search_node( pItemGroup , info.filepath_table ); print_unity_x( info ); clear_unity_file( pRoot ); add_unity_file( pRoot ); root.SaveFile( path.c_str() ); root.Clear(); }
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; }
bool CButtonTranslator::LoadKeymap(const CStdString &keymapPath) { TiXmlDocument xmlDoc; CLog::Log(LOGINFO, "Loading %s", keymapPath.c_str()); if (!xmlDoc.LoadFile(keymapPath)) { CLog::Log(LOGERROR, "Error loading keymap: %s, Line %d\n%s", keymapPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if ( strValue != "keymap") { CLog::Log(LOGERROR, "%s Doesn't contain <keymap>", keymapPath.c_str()); return false; } // run through our window groups TiXmlNode* pWindow = pRoot->FirstChild(); while (pWindow) { if (pWindow->Type() == TiXmlNode::ELEMENT) { int windowID = WINDOW_INVALID; const char *szWindow = pWindow->Value(); if (szWindow) { if (strcmpi(szWindow, "global") == 0) windowID = -1; else windowID = TranslateWindow(szWindow); } MapWindowActions(pWindow, windowID); } pWindow = pWindow->NextSibling(); } return true; }
bool CButtonTranslator::LoadLircMap() { // load our xml file, and fill up our mapping tables TiXmlDocument xmlDoc; // Load the config file CStdString lircmapPath = g_settings.GetUserDataItem("Lircmap.xml"); CLog::Log(LOGINFO, "Loading %s", lircmapPath.c_str()); if (!xmlDoc.LoadFile(lircmapPath)) { g_LoadErrorStr.Format("%s, Line %d\n%s", lircmapPath.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return true; // This is so people who don't have the file won't fail, just warn } lircRemotesMap.clear(); TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if (strValue != "lircmap") { g_LoadErrorStr.Format("%sl Doesn't contain <lircmap>", lircmapPath.c_str()); return false; } // run through our window groups TiXmlNode* pRemote = pRoot->FirstChild(); while (pRemote) { const char *szRemote = pRemote->Value(); if (szRemote) { TiXmlAttribute* pAttr = pRemote->ToElement()->FirstAttribute(); const char* szDeviceName = pAttr->Value(); MapRemote(pRemote, szDeviceName); } pRemote = pRemote->NextSibling(); } return true; }
bool CMediaManager::LoadSources() { CStdString xmlFile = _P(MEDIA_SOURCES_XML); // clear our location list m_locations.clear(); // load xml file... TiXmlDocument xmlDoc; if ( !xmlDoc.LoadFile( xmlFile.c_str() ) ) return false; TiXmlElement* pRootElement = xmlDoc.RootElement(); if ( !pRootElement || strcmpi(pRootElement->Value(), "mediasources") != 0) { CLog::Log(LOGERROR, "Error loading %s, Line %d (%s)", xmlFile.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } // load the <network> block TiXmlNode *pNetwork = pRootElement->FirstChild("network"); if (pNetwork) { TiXmlElement *pLocation = pNetwork->FirstChildElement("location"); while (pLocation) { CNetworkLocation location; pLocation->Attribute("id", &location.id); if (pLocation->FirstChild()) { location.path = pLocation->FirstChild()->Value(); m_locations.push_back(location); } pLocation = pLocation->NextSiblingElement("location"); } } return true; }
// \brief Load the config file (sounds.xml) for nav sounds // Can be located in a folder "sounds" in the skin or from a // subfolder of the folder "sounds" in the root directory of // xbmc bool CGUIAudioManager::Load() { CSingleLock lock(m_cs); m_actionSoundMap.clear(); m_windowSoundMap.clear(); if (g_guiSettings.GetString("lookandfeel.soundskin")=="OFF") return true; else Enable(true); if (g_guiSettings.GetString("lookandfeel.soundskin")=="SKINDEFAULT") { m_strMediaDir = CUtil::AddFileToFolder(g_SkinInfo->Path(), "sounds"); } else m_strMediaDir = CUtil::AddFileToFolder("special://xbmc/sounds", g_guiSettings.GetString("lookandfeel.soundskin")); CStdString strSoundsXml = CUtil::AddFileToFolder(m_strMediaDir, "sounds.xml"); // Load our xml file TiXmlDocument xmlDoc; CLog::Log(LOGINFO, "Loading %s", strSoundsXml.c_str()); // Load the config file if (!xmlDoc.LoadFile(strSoundsXml)) { CLog::Log(LOGNOTICE, "%s, Line %d\n%s", strSoundsXml.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if ( strValue != "sounds") { CLog::Log(LOGNOTICE, "%s Doesn't contain <sounds>", strSoundsXml.c_str()); return false; } // Load sounds for actions TiXmlElement* pActions = pRoot->FirstChildElement("actions"); if (pActions) { TiXmlNode* pAction = pActions->FirstChild("action"); while (pAction) { TiXmlNode* pIdNode = pAction->FirstChild("name"); int id = 0; // action identity if (pIdNode && pIdNode->FirstChild()) { CButtonTranslator::TranslateActionString(pIdNode->FirstChild()->Value(), id); } TiXmlNode* pFileNode = pAction->FirstChild("file"); CStdString strFile; if (pFileNode && pFileNode->FirstChild()) strFile+=pFileNode->FirstChild()->Value(); if (id > 0 && !strFile.IsEmpty()) m_actionSoundMap.insert(pair<int, CStdString>(id, strFile)); pAction = pAction->NextSibling(); } } // Load window specific sounds TiXmlElement* pWindows = pRoot->FirstChildElement("windows"); if (pWindows) { TiXmlNode* pWindow = pWindows->FirstChild("window"); while (pWindow) { int id = 0; TiXmlNode* pIdNode = pWindow->FirstChild("name"); if (pIdNode) { if (pIdNode->FirstChild()) id = CButtonTranslator::TranslateWindow(pIdNode->FirstChild()->Value()); } CWindowSounds sounds; LoadWindowSound(pWindow, "activate", sounds.strInitFile); LoadWindowSound(pWindow, "deactivate", sounds.strDeInitFile); if (id > 0) m_windowSoundMap.insert(pair<int, CWindowSounds>(id, sounds)); pWindow = pWindow->NextSibling(); } } return true; }
void CAdvancedSettings::ParseSettingsFile(const CStdString &file) { TiXmlDocument advancedXML; if (!CFile::Exists(file)) { CLog::Log(LOGNOTICE, "No settings file to load (%s)", file.c_str()); return; } if (!advancedXML.LoadFile(file)) { CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", file.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc()); return; } TiXmlElement *pRootElement = advancedXML.RootElement(); if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0) { CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", file.c_str()); return; } // succeeded - tell the user it worked CLog::Log(LOGNOTICE, "Loaded settings file from %s", file.c_str()); // Dump contents of AS.xml to debug log TiXmlPrinter printer; printer.SetLineBreak("\n"); printer.SetIndent(" "); advancedXML.Accept(&printer); CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", file.c_str(), printer.CStr()); TiXmlElement *pElement = pRootElement->FirstChildElement("audio"); if (pElement) { XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f); XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12); XMLUtils::GetString(pElement, "defaultplayer", m_audioDefaultPlayer); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0); XMLUtils::GetInt(pElement, "resample", m_musicResample, 0, 192000); TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps); pAudioExcludes = pElement->FirstChildElement("excludefromscan"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps); XMLUtils::GetString(pElement, "audiohost", m_audioHost); XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc); XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV); XMLUtils::GetFloat(pElement, "limiterhold", m_limiterHold, 0.0f, 100.0f); XMLUtils::GetFloat(pElement, "limiterrelease", m_limiterRelease, 0.001f, 100.0f); } pElement = pRootElement->FirstChildElement("karaoke"); if (pElement) { XMLUtils::GetFloat(pElement, "syncdelaycdg", m_karaokeSyncDelayCDG, -3.0f, 3.0f); // keep the old name for comp XMLUtils::GetFloat(pElement, "syncdelaylrc", m_karaokeSyncDelayLRC, -3.0f, 3.0f); XMLUtils::GetBoolean(pElement, "alwaysreplacegenre", m_karaokeChangeGenreForKaraokeSongs ); XMLUtils::GetBoolean(pElement, "storedelay", m_karaokeKeepDelay ); XMLUtils::GetInt(pElement, "autoassignstartfrom", m_karaokeStartIndex, 1, 2000000000); XMLUtils::GetBoolean(pElement, "nocdgbackground", m_karaokeAlwaysEmptyOnCdgs ); XMLUtils::GetBoolean(pElement, "lookupsongbackground", m_karaokeUseSongSpecificBackground ); TiXmlElement* pKaraokeBackground = pElement->FirstChildElement("defaultbackground"); if (pKaraokeBackground) { const char* attr = pKaraokeBackground->Attribute("type"); if ( attr ) m_karaokeDefaultBackgroundType = attr; attr = pKaraokeBackground->Attribute("path"); if ( attr ) m_karaokeDefaultBackgroundFilePath = attr; } } pElement = pRootElement->FirstChildElement("video"); if (pElement) { XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600); XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600); XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255); XMLUtils::GetString(pElement, "defaultplayer", m_videoDefaultPlayer); XMLUtils::GetString(pElement, "defaultdvdplayer", m_videoDefaultDVDPlayer); XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900); XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f); XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX); XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10); XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0); TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps); pVideoExcludes = pElement->FirstChildElement("excludefromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("cleanstrings"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps); XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp); XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint); XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc); XMLUtils::GetBoolean(pElement,"vdpauscaling",m_videoVDPAUScaling); XMLUtils::GetFloat(pElement, "nonlinearstretchratio", m_videoNonLinStretchRatio, 0.01f, 1.0f); XMLUtils::GetBoolean(pElement,"enablehighqualityhwscalers", m_videoEnableHighQualityHwScalers); XMLUtils::GetFloat(pElement,"autoscalemaxfps",m_videoAutoScaleMaxFps, 0.0f, 1000.0f); XMLUtils::GetBoolean(pElement,"allowmpeg4vdpau",m_videoAllowMpeg4VDPAU); XMLUtils::GetBoolean(pElement,"allowmpeg4vaapi",m_videoAllowMpeg4VAAPI); XMLUtils::GetBoolean(pElement, "disablebackgrounddeinterlace", m_videoDisableBackgroundDeinterlace); XMLUtils::GetInt(pElement, "useocclusionquery", m_videoCaptureUseOcclusionQuery, -1, 1); TiXmlElement* pAdjustRefreshrate = pElement->FirstChildElement("adjustrefreshrate"); if (pAdjustRefreshrate) { TiXmlElement* pRefreshOverride = pAdjustRefreshrate->FirstChildElement("override"); while (pRefreshOverride) { RefreshOverride override = {0}; float fps; if (XMLUtils::GetFloat(pRefreshOverride, "fps", fps)) { override.fpsmin = fps - 0.01f; override.fpsmax = fps + 0.01f; } float fpsmin, fpsmax; if (XMLUtils::GetFloat(pRefreshOverride, "fpsmin", fpsmin) && XMLUtils::GetFloat(pRefreshOverride, "fpsmax", fpsmax)) { override.fpsmin = fpsmin; override.fpsmax = fpsmax; } float refresh; if (XMLUtils::GetFloat(pRefreshOverride, "refresh", refresh)) { override.refreshmin = refresh - 0.01f; override.refreshmax = refresh + 0.01f;
int main() { // // We start with the 'demoStart' todo list. Process it. And // should hopefully end up with the todo list as illustrated. // const char* demoStart = "<?xml version=\"1.0\" standalone='no' >\n" "<!-- Our to do list data -->" "<ToDo>\n" "<!-- Do I need a secure PDA? -->\n" "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>" "<Item priority=\"2\" distance='none'> Do bills </Item>" "<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>" "</ToDo>"; { #ifdef TIXML_USE_STL // What the todo list should look like after processing. // In stream (no formatting) representation. const char* demoEnd = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<!-- Our to do list data -->" "<ToDo>" "<!-- Do I need a secure PDA? -->" "<Item priority=\"2\" distance=\"close\">Go to the" "<bold>Toy store!" "</bold>" "</Item>" "<Item priority=\"1\" distance=\"far\">Talk to:" "<Meeting where=\"School\">" "<Attendee name=\"Marple\" position=\"teacher\" />" "<Attendee name=\"Voel\" position=\"counselor\" />" "</Meeting>" "<Meeting where=\"Lunch\" />" "</Item>" "<Item priority=\"2\" distance=\"here\">Do bills" "</Item>" "</ToDo>"; #endif // The example parses from the character string (above): #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &startMemState ); #endif { // Write to a file and read it back, to check file I/O. TiXmlDocument doc( "demotest.xml" ); doc.Parse( demoStart ); if ( doc.Error() ) { printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() ); exit( 1 ); } doc.SaveFile(); } TiXmlDocument doc( "demotest.xml" ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() ); exit( 1 ); } printf( "** Demo doc read from disk: ** \n\n" ); printf( "** Printing via doc.Print **\n" ); doc.Print( stdout ); { printf( "** Printing via TiXmlPrinter **\n" ); TiXmlPrinter printer; doc.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); } #ifdef TIXML_USE_STL { printf( "** Printing via operator<< **\n" ); std::cout << doc; } #endif TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChildElement(); // This skips the "PDA" comment. assert( node ); itemElement = node->ToElement(); assert( itemElement ); itemElement->SetAttribute( "priority", 2 ); // Change the distance to "doing bills" from // "none" to "here". It's the next sibling element. itemElement = itemElement->NextSiblingElement(); assert( itemElement ); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil Dinosaurs!" item. // It is 1 more sibling away. We ask the parent to remove // a particular child. itemElement = itemElement->NextSiblingElement(); todoElement->RemoveChild( itemElement ); itemElement = 0; // -------------------------------------------------------- // What follows is an example of created elements and text // nodes and adding them to the document. // -------------------------------------------------------- // Add some meetings. TiXmlElement item( "Item" ); item.SetAttribute( "priority", "1" ); item.SetAttribute( "distance", "far" ); TiXmlText text( "Talk to:" ); TiXmlElement meeting1( "Meeting" ); meeting1.SetAttribute( "where", "School" ); TiXmlElement meeting2( "Meeting" ); meeting2.SetAttribute( "where", "Lunch" ); TiXmlElement attendee1( "Attendee" ); attendee1.SetAttribute( "name", "Marple" ); attendee1.SetAttribute( "position", "teacher" ); TiXmlElement attendee2( "Attendee" ); attendee2.SetAttribute( "name", "Voel" ); attendee2.SetAttribute( "position", "counselor" ); // Assemble the nodes we've created: meeting1.InsertEndChild( attendee1 ); meeting1.InsertEndChild( attendee2 ); item.InsertEndChild( text ); item.InsertEndChild( meeting1 ); item.InsertEndChild( meeting2 ); // And add the node to the existing list after the first child. node = todoElement->FirstChild( "Item" ); assert( node ); itemElement = node->ToElement(); assert( itemElement ); todoElement->InsertAfterChild( itemElement, item ); printf( "\n** Demo doc processed: ** \n\n" ); doc.Print( stdout ); #ifdef TIXML_USE_STL printf( "** Demo doc processed to stream: ** \n\n" ); cout << doc << endl << endl; #endif // -------------------------------------------------------- // Different tests...do we have what we expect? // -------------------------------------------------------- int count = 0; TiXmlElement* element; ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL cout << "** Basic structure. **\n"; ostringstream outputStream( ostringstream::out ); outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), outputStream.str().c_str(), true ); #endif node = doc.RootElement(); assert( node ); XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Root element value is 'ToDo'.", "ToDo", node->Value()); node = node->FirstChild(); XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) ); node = node->NextSibling(); XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Value is 'Item'.", "Item", node->Value() ); node = node->FirstChild(); XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) ); XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() ); ////////////////////////////////////////////////////// printf ("\n** Iterators. **\n"); // Walk all the top level nodes of the document. count = 0; for( node = doc.FirstChild(); node; node = node->NextSibling() ) { count++; } XmlTest( "Top level nodes, using First / Next.", 3, count ); count = 0; for( node = doc.LastChild(); node; node = node->PreviousSibling() ) { count++; } XmlTest( "Top level nodes, using Last / Previous.", 3, count ); // Walk all the top level nodes of the document, // using a different syntax. count = 0; for( node = doc.IterateChildren( 0 ); node; node = doc.IterateChildren( node ) ) { count++; } XmlTest( "Top level nodes, using IterateChildren.", 3, count ); // Walk all the elements in a node. count = 0; for( element = todoElement->FirstChildElement(); element; element = element->NextSiblingElement() ) { count++; } XmlTest( "Children of the 'ToDo' element, using First / Next.", 3, count ); // Walk all the elements in a node by value. count = 0; for( node = todoElement->FirstChild( "Item" ); node; node = node->NextSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count ); count = 0; for( node = todoElement->LastChild( "Item" ); node; node = node->PreviousSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count ); #ifdef TIXML_USE_STL { cout << "\n** Parsing. **\n"; istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '>' />" ); TiXmlElement element0( "default" ); parse0 >> element0; XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() ); XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" )); XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) ); XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) ); } #endif { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; TiXmlDocument docTest; docTest.Parse( error ); XmlTest( "Error row", docTest.ErrorRow(), 3 ); XmlTest( "Error column", docTest.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } #ifdef TIXML_USE_STL { ////////////////////////////////////////////////////// cout << "\n** Streaming. **\n"; // Round trip check: stream in, then stream back out to verify. The stream // out has already been checked, above. We use the output istringstream inputStringStream( outputStream.str() ); TiXmlDocument document0; inputStringStream >> document0; ostringstream outputStream0( ostringstream::out ); outputStream0 << document0; XmlTest( "Stream round trip correct.", string( demoEnd ).c_str(), outputStream0.str().c_str(), true ); std::string str; str << document0; XmlTest( "String printing correct.", string( demoEnd ).c_str(), str.c_str(), true ); } #endif } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); XmlTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE ); } { const char* str = "<doc/>"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal; double dVal; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetDoubleAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); XmlTest( "Attribute round trip. c-string.", "strValue", cStr ); XmlTest( "Attribute round trip. int.", 1, iVal ); XmlTest( "Attribute round trip. double.", -1, (int)dVal ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" "</room>"; TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); assert( docHandle.Node() ); assert( roomHandle.Element() ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 ); XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 ); XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" " <!-- Silly example -->\n" " <door wall='north'>A great door!</door>\n" "\t<door wall='east'/>" "</room>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild(); TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild(); TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 ); TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 ); assert( docHandle.Node() ); assert( roomHandle.Element() ); assert( commentHandle.Node() ); assert( textHandle.Text() ); assert( door0Handle.Element() ); assert( door1Handle.Element() ); TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration(); assert( declaration ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); TiXmlText* text = textHandle.Text(); TiXmlComment* comment = commentHandle.Node()->ToComment(); assert( comment ); TiXmlElement* door0 = door0Handle.Element(); TiXmlElement* door1 = door1Handle.Element(); XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 ); XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 ); XmlTest( "Location tracking: room row", room->Row(), 1 ); XmlTest( "Location tracking: room col", room->Column(), 45 ); XmlTest( "Location tracking: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: doors col", doors->Column(), 51 ); XmlTest( "Location tracking: Comment row", comment->Row(), 2 ); XmlTest( "Location tracking: Comment col", comment->Column(), 3 ); XmlTest( "Location tracking: text row", text->Row(), 3 ); XmlTest( "Location tracking: text col", text->Column(), 24 ); XmlTest( "Location tracking: door0 row", door0->Row(), 3 ); XmlTest( "Location tracking: door0 col", door0->Column(), 5 ); XmlTest( "Location tracking: door1 row", door1->Row(), 4 ); XmlTest( "Location tracking: door1 col", door1->Column(), 5 ); } // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "data/utf8testout.xml", "r" ); FILE* verify = fopen( "data/utf8testverify.xml", "r" ); //bool firstLineBOM=true; if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( /*!firstLineBOM && */ strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); okay = 0; break; } //firstLineBOM = false; } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else completely on non-wester machines, // which is why TinyXml is switching to UTF-8. const char latin[] = "<element>r\x82sum\x82</element>"; TiXmlDocument latinDoc; latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY ); text = latinDoc.FirstChildElement()->FirstChild()->ToText(); XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() ); } } ////////////////////// // Copy and assignment ////////////////////// printf ("\n** Copy and Assignment **\n"); { TiXmlElement element( "foo" ); element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN ); TiXmlElement elementCopy( element ); TiXmlElement elementAssign( "foo" ); elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN ); elementAssign = element; XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() ); XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() ); XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) ); TiXmlComment comment; comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN ); TiXmlComment commentCopy( comment ); TiXmlComment commentAssign; commentAssign = commentCopy; XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() ); XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() ); TiXmlUnknown unknown; unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlUnknown unknownCopy( unknown ); TiXmlUnknown unknownAssign; unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN ); unknownAssign = unknownCopy; XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() ); XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() ); TiXmlText text( "TextNode" ); TiXmlText textCopy( text ); TiXmlText textAssign( "incorrect" ); textAssign = text; XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() ); XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() ); TiXmlDeclaration dec; dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlDeclaration decCopy( dec ); TiXmlDeclaration decAssign; decAssign = dec; XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() ); XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() ); TiXmlDocument doc; elementCopy.InsertEndChild( textCopy ); doc.InsertEndChild( decAssign ); doc.InsertEndChild( elementCopy ); doc.InsertEndChild( unknownAssign ); TiXmlDocument docCopy( doc ); TiXmlDocument docAssign; docAssign = docCopy; #ifdef TIXML_USE_STL std::string original, copy, assign; original << doc; copy << docCopy; assign << docAssign; XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true ); XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true ); #endif } ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL printf ("\n** Parsing, no Condense Whitespace **\n"); TiXmlBase::SetCondenseWhiteSpace( false ); { istringstream parse1( "<start>This is \ntext</start>" ); TiXmlElement text1( "text" ); parse1 >> text1; XmlTest ( "Condense white space OFF.", "This is \ntext", text1.FirstChild()->Value(), true ); } TiXmlBase::SetCondenseWhiteSpace( true ); #endif ////////////////////////////////////////////////////// // GetText(); { const char* str = "<foo>This is text</foo>"; TiXmlDocument doc; doc.Parse( str ); const TiXmlElement* element = doc.RootElement(); XmlTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Clear(); doc.Parse( str ); element = doc.RootElement(); XmlTest( "GetText() contained element.", element->GetText() == 0, true ); str = "<foo>This is <b>text</b></foo>"; doc.Clear(); TiXmlBase::SetCondenseWhiteSpace( false ); doc.Parse( str ); TiXmlBase::SetCondenseWhiteSpace( true ); element = doc.RootElement(); XmlTest( "GetText() partial.", "This is ", element->GetText() ); } ////////////////////////////////////////////////////// // CDATA { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL //cout << doc << '\n'; doc.Clear(); istringstream parse0( str ); parse0 >> doc; //cout << doc << '\n'; XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); } { // [ 1482728 ] Wrong wide char parsing char buf[256]; buf[255] = 0; for( int i=0; i<255; ++i ) { buf[i] = (char)((i>=32) ? i : 32); } TIXML_STRING str( "<xmlElement><![CDATA[" ); str += buf; str += "]]></xmlElement>"; TiXmlDocument doc; doc.Parse( str.c_str() ); TiXmlPrinter printer; printer.SetStreamPrinting(); doc.Accept( &printer ); XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream iss( printer.Str() ); iss >> doc; std::string out; out << doc; XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true ); #endif } { // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags // CDATA streaming had a couple of bugs, that this tests for. const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream parse0( str ); parse0 >> doc; XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); } ////////////////////////////////////////////////////// // Visit() ////////////////////////////////////////////////////// printf( "\n** Fuzzing... **\n" ); const int FUZZ_ITERATION = 300; // The only goal is not to crash on bad input. int len = (int) strlen( demoStart ); for( int i=0; i<FUZZ_ITERATION; ++i ) { char* demoCopy = new char[ len+1 ]; strcpy( demoCopy, demoStart ); demoCopy[ i%len ] = (char)((i+1)*3); demoCopy[ (i*7)%len ] = '>'; demoCopy[ (i*11)%len ] = '<'; TiXmlDocument xml; xml.Parse( demoCopy ); delete [] demoCopy; } printf( "** Fuzzing Complete. **\n" ); ////////////////////////////////////////////////////// printf ("\n** Bug regression tests **\n"); // InsertBeforeChild and InsertAfterChild causes crash. { TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 ); XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true ); } { // InsertBeforeChild and InsertAfterChild causes crash. TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 ); XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true ); } // Reports of missing constructors, irregular string problems. { // Missing constructor implementation. No test -- just compiles. TiXmlText text( "Missing" ); #ifdef TIXML_USE_STL // Missing implementation: TiXmlDocument doc; string name = "missing"; doc.LoadFile( name ); TiXmlText textSTL( name ); #else // verifying some basic string functions: TiXmlString a; TiXmlString b( "Hello" ); TiXmlString c( "ooga" ); c = " World!"; a = b; a += c; a = a; XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() ); #endif } // Long filenames crashing STL version { TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" ); bool loadOkay = doc.LoadFile(); loadOkay = true; // get rid of compiler warning. // Won't pass on non-dev systems. Just a "no crash" check. //XmlTest( "Long filename. ", true, loadOkay ); } { // Entities not being written correctly. // From Lynn Allen const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright ©.\"> </psg>" "</passages>"; TiXmlDocument doc( "passages.xml" ); doc.Parse( passages ); TiXmlElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9."; XmlTest( "Entity transformation: read. ", expected, context, true ); FILE* textfile = fopen( "textfile.txt", "w" ); if ( textfile ) { psg->Print( textfile, 0 ); fclose( textfile ); } textfile = fopen( "textfile.txt", "r" ); assert( textfile ); if ( textfile ) { char buf[ 1024 ]; fgets( buf, 1024, textfile ); XmlTest( "Entity transformation: write. ", "<psg context=\'Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright \xC2\xA9.' />", buf, true ); } fclose( textfile ); } { FILE* textfile = fopen( "test5.xml", "w" ); if ( textfile ) { fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile); fclose(textfile); TiXmlDocument doc; doc.LoadFile( "test5.xml" ); XmlTest( "dot in element attributes and names", doc.Error(), 0); } } { FILE* textfile = fopen( "test6.xml", "w" ); if ( textfile ) { fputs("<element><Name>1.1 Start easy ignore fin thickness
</Name></element>", textfile ); fclose(textfile); TiXmlDocument doc; bool result = doc.LoadFile( "test6.xml" ); XmlTest( "Entity with one digit.", result, true ); TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XmlTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n" ); } } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; TiXmlDocument doc; doc.Parse( doctype ); doc.SaveFile( "test7.xml" ); doc.Clear(); doc.LoadFile( "test7.xml" ); TiXmlHandle docH( &doc ); TiXmlUnknown* unknown = docH.Child( 1 ).Unknown(); XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() ); #ifdef TIXML_USE_STL TiXmlNode* node = docH.Child( 2 ).Node(); std::string str; str << (*node); XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() ); #endif } { // [ 791411 ] Formatting bug // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; TiXmlDocument doc; doc.Parse( doctype ); TiXmlHandle docH( &doc ); TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment(); XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); #ifdef TIXML_USE_STL std::string str; str << (*comment); XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() ); #endif } { // [ 870502 ] White space issues TiXmlDocument doc; TiXmlText* text; TiXmlHandle docH( &doc ); const char* doctype0 = "<element> This has leading and trailing space </element>"; const char* doctype1 = "<element>This has internal space</element>"; const char* doctype2 = "<element> This has leading, trailing, and internal space </element>"; TiXmlBase::SetCondenseWhiteSpace( false ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading, trailing, and internal space ", text->Value() ); TiXmlBase::SetCondenseWhiteSpace( true ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Parsing repeated attributes.", true, doc.Error() ); // is an error to tinyxml (didn't use to be, but caused issues) //XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { /** // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<?" "C鰊t鋘t咪鳇闹?" "</?"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "?" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "C鰊t鋘t咪鳇闹?, tHandle.Text()->Value() "); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // Bug [ 1195696 ] from marlonism TiXmlBase::SetCondenseWhiteSpace(false); TiXmlDocument xml; xml.Parse("<text><break/>This hangs</text>"); XmlTest( "Test safe error return.", xml.Error(), false ); } { // Bug [ 1243992 ] - another infinite loop TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); doc.Parse("<p><pb></pb>test</p>"); } { // Low entities TiXmlDocument xml; xml.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result ); xml.Print(); } { // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly TiXmlDocument xml; xml.Parse( "<foo attribute=bar\" />" ); XmlTest( "Throw error with bad end quotes.", xml.Error(), true ); } #ifdef TIXML_USE_STL { // Bug [ 1449463 ] Consider generic query TiXmlDocument xml; xml.Parse( "<foo bar='3' barStr='a string'/>" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; float f; bool b; std::string str; XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", (d==3.0), true ); XmlTest( "QueryValueAttribute", (i==3), true ); XmlTest( "QueryValueAttribute", (f==3.0f), true ); XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true ); } #endif #ifdef TIXML_USE_STL { // [ 1505267 ] redundant malloc in TiXmlElement::Attribute TiXmlDocument xml; xml.Parse( "<foo bar='3' />" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; std::string bar = "bar"; const std::string* atrrib = ele->Attribute( bar ); ele->Attribute( bar, &d ); ele->Attribute( bar, &i ); XmlTest( "Attribute", atrrib->empty(), false ); XmlTest( "Attribute", (d==3.0), true ); XmlTest( "Attribute", (i==3), true ); } #endif { // [ 1356059 ] Allow TiXMLDocument to only be at the top level TiXmlDocument xml, xml2; xml.InsertEndChild( xml2 ); XmlTest( "Document only at top level.", xml.Error(), true ); XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY ); } { // [ 1663758 ] Failure to report error on bad XML TiXmlDocument xml; xml.Parse("<x>"); XmlTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XmlTest("Missing end tag with trailing whitespace", xml.Error(), true); } { // [ 1635701 ] fail to parse files with a tag separated into two lines // I'm not sure this is a bug. Marked 'pending' for feedback. TiXmlDocument xml; xml.Parse( "<title><p>text</p\n><title>" ); //xml.Print(); //XmlTest( "Tag split by newline", xml.Error(), false ); } #ifdef TIXML_USE_STL { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; istringstream parse1( "<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); parse1 >> xml; TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } #endif { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } { TiXmlDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); int count = 0; TiXmlNode* ele = 0; while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) { ++count; } XmlTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; TiXmlDocument doc; doc.Parse( (const char*)buf); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. TiXmlDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XmlTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop TiXmlDocument xml; xml.Parse( "<infinite>loop" ); XmlTest( "Infinite loop test.", true, true ); } { // 1709904 - can not repro the crash { TiXmlDocument xml; xml.Parse( "<tag>/</tag>" ); XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" ); } /* Could not repro. { TiXmlDocument xml; xml.LoadFile( "EQUI_Inventory.xml" ); //XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" ); TiXmlPrinter printer; xml.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); }*/ } /* 1417717 experiment { TiXmlDocument xml; xml.Parse("<text>Dan & Tracie</text>"); xml.Print(stdout); } { TiXmlDocument xml; xml.Parse("<text>Dan &foo; Tracie</text>"); xml.Print(stdout); } */ #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
static bool load_registry_xml(char* filename) { TiXmlDocument doc; if(!doc.LoadFile(filename)) { if(doc.ErrorId() != TiXmlBase::TIXML_ERROR_OPENING_FILE) CLog::Log(LOGERROR, __FUNCTION__"(%s) - %s on row %d and col %d", filename, doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol()); return false; } if(strcmp("registry", doc.RootElement()->Value())) { CLog::Log(LOGERROR, __FUNCTION__"(%s) - Invalid root element expected ""registry""", doc.RootElement()->Value()); return false; } TiXmlNode *node = NULL; while(node = doc.RootElement()->IterateChildren("key", node)) load_registry_key(0, node->ToElement()); return true; }
bool CScrobbler::LoadJournal() { int journalVersion = 0; SubmissionJournalEntry entry; TiXmlDocument xmlDoc; CStdString JournalFileName = GetJournalFileName(); CSingleLock lock(m_queueLock); m_vecSubmissionQueue.clear(); if (!xmlDoc.LoadFile(JournalFileName)) { CLog::Log(LOGDEBUG, "%s: %s, Line %d (%s)", m_strLogPrefix.c_str(), JournalFileName.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement *pRoot = xmlDoc.RootElement(); if (strcmpi(pRoot->Value(), "asjournal") != 0) { CLog::Log(LOGDEBUG, "%s: %s missing <asjournal>", m_strLogPrefix.c_str(), JournalFileName.c_str()); return false; } if (pRoot->Attribute("version")) journalVersion = atoi(pRoot->Attribute("version")); TiXmlNode *pNode = pRoot->FirstChild("entry"); for (; pNode; pNode = pNode->NextSibling("entry")) { entry.Clear(); XMLUtils::GetString(pNode, "artist", entry.strArtist); XMLUtils::GetString(pNode, "album", entry.strAlbum); XMLUtils::GetString(pNode, "title", entry.strTitle); XMLUtils::GetString(pNode, "length", entry.strLength); entry.length = atoi(entry.strLength.c_str()); XMLUtils::GetString(pNode, "starttime", entry.strStartTime); XMLUtils::GetString(pNode, "musicbrainzid", entry.strMusicBrainzID); if (journalVersion > 0) { XMLUtils::GetString(pNode, "tracknum", entry.strTrackNum); XMLUtils::GetString(pNode, "source", entry.strSource); XMLUtils::GetString(pNode, "rating", entry.strRating); } else { // Update from journal v0 // Convert start time stamp struct tm starttm; time_t startt; if (!strptime(entry.strStartTime.c_str(), "%Y-%m-%d %H:%M:%S", &starttm)) continue; if ((startt = mktime(&starttm)) == -1) continue; entry.strStartTime.Format("%d", startt); // url encode entries CURL::Encode(entry.strArtist); CURL::Encode(entry.strTitle); CURL::Encode(entry.strAlbum); CURL::Encode(entry.strMusicBrainzID); } m_vecSubmissionQueue.push_back(entry); } CLog::Log(LOGDEBUG, "%s: Journal loaded with %"PRIuS" entries.", m_strLogPrefix.c_str(), m_vecSubmissionQueue.size()); return !m_vecSubmissionQueue.empty(); }
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; }
bool RequestBaseTask::HandleResult(const char* buf, int size, string &errnum, string &errmsg, TiXmlDocument &doc, bool* bContinue) { bool bFlag = false; bool bIsParseSuccess = false; if( bContinue != NULL ) { *bContinue = true; } /* try to parse xml */ TiXmlElement* itemElement; doc.Parse(buf); const char *p = NULL; if ( !doc.Error() ) { TiXmlNode *rootNode = doc.FirstChild(COMMON_ROOT); if( rootNode != NULL ) { TiXmlNode *resultNode = rootNode->FirstChild(COMMON_RESULT); if( resultNode != NULL ) { bIsParseSuccess = true; TiXmlNode *statusNode = resultNode->FirstChild(COMMON_STATUS); if( statusNode != NULL ) { itemElement = statusNode->ToElement(); if ( itemElement != NULL ) { p = itemElement->GetText(); if( p != NULL && 1 == atoi(p) ) { bFlag = true; } } } TiXmlNode *errcodeNode = resultNode->FirstChild(COMMON_ERRCODE); if( errcodeNode != NULL ) { itemElement = errcodeNode->ToElement(); if ( itemElement != NULL ) { p = itemElement->GetText(); if( p != NULL ) { errnum = p; if( mpErrcodeHandler != NULL ) { bool bc = mpErrcodeHandler->ErrcodeHandle(this, errnum); if( bContinue != NULL ) { *bContinue = bc; } } } } } TiXmlNode *errmsgNode = resultNode->FirstChild(COMMON_ERRMSG); if( errmsgNode != NULL ) { itemElement = errmsgNode->ToElement(); if ( itemElement != NULL ) { p = itemElement->GetText(); if( p != NULL ) { errmsg = p; } } } } } } // parse protocol fail if (!bIsParseSuccess) { errnum = LOCAL_ERROR_CODE_PARSEFAIL; errmsg = LOCAL_ERROR_CODE_PARSEFAIL_DESC; } FileLog("httprequest", "RequestBaseTask::HandleResult( " "Value() : %s, " "ErrorDesc() : %s, " "ErrorRow() : %d, " "ErrorCol() : %d " ")", doc.Value(), doc.ErrorDesc(), doc.ErrorRow(), doc.ErrorCol() ); mErrCode = errnum; return bFlag; }
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; }
bool XmlAppSaver::serialXml(Application* app, const char* szFile) { // updating application xml file name app->setXmlFile(szFile); ErrorLogger* logger = ErrorLogger::Instance(); TiXmlDocument doc; //(szFile); TiXmlElement * root = new TiXmlElement("application"); doc.LinkEndChild( root ); TiXmlElement * appName = new TiXmlElement("name"); //are all these NEW ok? appName->LinkEndChild(new TiXmlText(app->getName())); root->LinkEndChild(appName); if (strcmp(app->getDescription(), "")) { TiXmlElement * desc= new TiXmlElement( "description"); desc->LinkEndChild(new TiXmlText( app->getDescription())); root->LinkEndChild(desc); } if(strcmp (app->getVersion(), "")) { TiXmlElement * vers= new TiXmlElement( "version"); vers->LinkEndChild(new TiXmlText( app->getVersion())); root->LinkEndChild(vers); } /* * TODO: setting prefix of the main application is inactivated. * Check this should be supported in future or not! */ /* if(strcmp (app->getPrefix(), "")) { TiXmlElement * prefix= new TiXmlElement( "prefix"); prefix->LinkEndChild(new TiXmlText( app->getPrefix())); root->LinkEndChild(prefix); } */ if(app->authorCount()>0) { TiXmlElement *auths=new TiXmlElement("authors"); for (int i=0; i<app->authorCount(); i++) { //app->getAuthorAt(i); TiXmlElement *auth=new TiXmlElement("author"); auth->SetAttribute("email", app->getAuthorAt(i).getEmail()); auth->LinkEndChild(new TiXmlText(app->getAuthorAt(i).getName())); auths->LinkEndChild(auth); } root->LinkEndChild(auths); } // iterate over modules { int nModules=app->imoduleCount(); for (int modCt=0; modCt<nModules; ++modCt) { TiXmlElement * newMod = new TiXmlElement("module"); root->LinkEndChild(newMod); //add module element ModuleInterface curMod=app->getImoduleAt(modCt); TiXmlElement *name = new TiXmlElement("name"); name->LinkEndChild(new TiXmlText(curMod.getName())); newMod->LinkEndChild(name); TiXmlElement *parameters=new TiXmlElement("parameters"); parameters->LinkEndChild(new TiXmlText(curMod.getParam())); newMod->LinkEndChild(parameters); TiXmlElement *node = new TiXmlElement("node"); node->LinkEndChild(new TiXmlText(curMod.getHost())); //is host the same as node? newMod->LinkEndChild(node); TiXmlElement *prefix=new TiXmlElement("prefix"); prefix->LinkEndChild(new TiXmlText(curMod.getPrefix())); newMod->LinkEndChild(prefix); if(strcmp(curMod.getStdio(), "")) { TiXmlElement *stdio=new TiXmlElement("stdio"); stdio->LinkEndChild(new TiXmlText(curMod.getStdio())); newMod->LinkEndChild(stdio); } if(strcmp(curMod.getWorkDir(), "")) { TiXmlElement *workdir=new TiXmlElement("workdir"); workdir->LinkEndChild(new TiXmlText(curMod.getWorkDir())); newMod->LinkEndChild(workdir); } if(strcmp(curMod.getBroker(), "")) { TiXmlElement *broker=new TiXmlElement("deployer"); broker->LinkEndChild(new TiXmlText(curMod.getBroker())); newMod->LinkEndChild(broker); } /* if(curMod.getRank()>0) //TODO check here how is rank handled { TiXmlElement *rank=new TiXmlElement("rank"); char str[256]; sprintf(str,"%d", curMod.getRank()); rank->LinkEndChild(new TiXmlText(str)); newMod->LinkEndChild(rank); } */ GraphicModel model = curMod.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos (x "<<model.points[0].x<<") "<<"(y "<<model.points[0].y<<"))"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newMod->LinkEndChild(geometry); } } } // iterate over embedded applications { int nApps=app->iapplicationCount(); for (int appCt=0; appCt<nApps; ++appCt) { TiXmlElement *newApp = new TiXmlElement("application"); root->LinkEndChild(newApp); //add application element ApplicationInterface curApp=app->getIapplicationAt(appCt); TiXmlElement *name = new TiXmlElement("name"); name->LinkEndChild(new TiXmlText(curApp.getName())); newApp->LinkEndChild(name); TiXmlElement *prefix=new TiXmlElement("prefix"); prefix->LinkEndChild(new TiXmlText(curApp.getPrefix())); newApp->LinkEndChild(prefix); GraphicModel model = curApp.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos (x "<<model.points[0].x<<") "<<"(y "<<model.points[0].y<<"))"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newApp->LinkEndChild(geometry); } } } // iterate over connections { int nConns=app->connectionCount(); for (int connCt=0; connCt<nConns; ++connCt) { TiXmlElement *newConn=new TiXmlElement("connection"); Connection curConn=app->getConnectionAt(connCt); if(strlen(curConn.getId())) newConn->SetAttribute("id", curConn.getId()); if(curConn.isPersistent()) newConn->SetAttribute("persist", "true"); TiXmlElement *from = new TiXmlElement("from"); if (curConn.isExternalFrom()) from->SetAttribute("external", "true"); from->LinkEndChild(new TiXmlText(curConn.from())); newConn->LinkEndChild(from); TiXmlElement *to = new TiXmlElement("to"); if (curConn.isExternalTo()) to->SetAttribute("external", "true"); to->LinkEndChild(new TiXmlText(curConn.to())); newConn->LinkEndChild(to); TiXmlElement *protocol = new TiXmlElement("protocol"); protocol->LinkEndChild(new TiXmlText(curConn.carrier())); newConn->LinkEndChild(protocol); GraphicModel model = curConn.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos "; for(unsigned int i=0; i<model.points.size(); i++) txt<<"((x "<<model.points[i].x<<") "<<"(y "<<model.points[i].y<<")) "; txt<<" )"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newConn->LinkEndChild(geometry); } root->LinkEndChild(newConn); } } // iterate over arbitrators for(int i=0; i<app->arbitratorCount(); i++) { Arbitrator& arb = app->getArbitratorAt(i); TiXmlElement *newArb = new TiXmlElement("arbitrator"); TiXmlElement *port = new TiXmlElement("port"); port->LinkEndChild(new TiXmlText(arb.getPort())); newArb->LinkEndChild(port); std::map<string, string> &rules = arb.getRuleMap(); for(std::map<string, string>::iterator it=rules.begin(); it!=rules.end(); ++it) { TiXmlElement *rule = new TiXmlElement("rule"); rule->SetAttribute("connection", it->first.c_str()); rule->LinkEndChild(new TiXmlText(it->second.c_str())); newArb->LinkEndChild(rule); } GraphicModel model = arb.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos "; for(unsigned int i=0; i<model.points.size(); i++) txt<<"((x "<<model.points[i].x<<") "<<"(y "<<model.points[i].y<<")) "; txt<<" )"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newArb->LinkEndChild(geometry); } root->LinkEndChild(newArb); } bool ok=doc.SaveFile(app->getXmlFile()); if (!ok) { OSTRINGSTREAM err; err<<"tinyXml error for file " << app->getXmlFile(); if (doc.Error()) err <<" at line " << doc.ErrorRow() << ", column " << doc.ErrorCol() << ": " << doc.ErrorDesc(); logger->addError(err); err <<"\n"; return false; } else return true; }
bool wxsItemResData::LoadInSourceMode() { // TODO: Check if source / header files have required blocks of code TiXmlDocument Doc; if ( !TinyXML::LoadDocument(m_WxsFileName,&Doc) ) { Manager::Get()->GetLogManager()->DebugLog(F(_T("wxSmith: Error loading wxs file (Col: %d, Row:%d): ") + cbC2U(Doc.ErrorDesc()),Doc.ErrorCol(),Doc.ErrorRow())); return false; } TiXmlElement* wxSmithNode = Doc.FirstChildElement("wxsmith"); if ( !wxSmithNode ) return false; TiXmlElement* Object = wxSmithNode->FirstChildElement("object"); if ( !Object ) return false; /* if ( cbC2U(Object->Attribute("name")) != m_ClassName ) return false; if ( cbC2U(Object->Attribute("class")) != m_ClassType ) return false; */ RecreateRootItem(); if ( !m_RootItem ) return false; m_RootItem->XmlRead(Object,true,true); LoadToolsReq(Object,true,true); return true; }