void LevelParser::parseTileLayer(TiXmlElement* pTileElement, std::vector<Layer*> *pLayers, const std::vector<Tileset>* pTilesets, std::vector<TileLayer*> *m_CollisionsLayer) { TileLayer* pTileLayer = new TileLayer(m_tileSizew, m_tileSizeh, *pTilesets); bool collidable = false; std::vector<std::vector<int>> data; std::string decodedIDs; TiXmlElement* pDataNode; for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == std::string("properties")) { for (TiXmlElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement()) { if (property->Value() == std::string("property")) { if (property->Attribute("name") == std::string("collidable")) { collidable = true; } } } } if (e->Value() == std::string("data")) { pDataNode = e; } } for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()) { TiXmlText* text = e->ToText(); std::string t = text->Value(); decodedIDs = base64_decode(t); } uLongf numGids = m_width * m_height * sizeof(int); std::vector<unsigned> gids(numGids); uncompress((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); std::vector<int> layerRow(m_width); for (int j = 0; j < m_height; j++) { data.push_back(layerRow); } for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width; cols++) { data[rows][cols] = gids[rows * m_width + cols]; } } if (collidable) { m_CollisionsLayer->push_back(pTileLayer); } pTileLayer->setTileIDs(data); pLayers->push_back(pTileLayer); }
/// Visit a text node virtual bool Visit( const TiXmlText& text ) { // record text content _last_text = text.Value(); // dbg out << "text::Visit " << _last_text << endl; return true; }
void XMLTester::dump_to_stdout( TiXmlNode* pParent, unsigned int indent) { if ( !pParent ) return; TiXmlNode* pChild; TiXmlText* pText; int t = pParent->Type(); printf( "%s", xml_getIndent(indent)); int num; switch ( t ) { case TiXmlNode::DOCUMENT: printf( "Document" ); break; case TiXmlNode::ELEMENT: printf( "Element [%s]", pParent->Value() ); num=dump_attribs_to_stdout(pParent->ToElement(), indent+1); switch(num) { case 0: printf( " (No attributes)"); break; case 1: printf( "%s1 attribute", getIndentAlt(indent)); break; default: printf( "%s%d attributes", getIndentAlt(indent), num); break; } break; case TiXmlNode::COMMENT: printf( "Comment: [%s]", pParent->Value()); break; case TiXmlNode::UNKNOWN: printf( "Unknown" ); break; case TiXmlNode::TEXT: pText = pParent->ToText(); printf( "Text: [%s]", pText->Value() ); break; case TiXmlNode::DECLARATION: printf( "Declaration" ); break; default: break; } printf( "\n" ); for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { dump_to_stdout( pChild, indent+1 ); } }
CString CXmlElement::GetValue() { TiXmlText* temp = (TiXmlText*)_elem->FirstChild(); CString ret; if(temp != NULL){ ret = temp->Value(); } return ret; }
//takes the current <ar> node pointer and gets the word and definition for it //Then moves the pointer on to the next <ar> node (or 'end' if no more found) // //Note, I find the formatting of the definition within the node bizzarre as the //definition can be split into several blocks, with nodes embedded with the text. //Not the way I'd define a dictionary schema, but hey, its free and comprehensive //so I can't really complain. TiXmlElement* Words2::xdxfNextWord(TiXmlElement* ar, std::string &word, std::string &def) { if (!_doc) return 0; TiXmlElement *tmpElement; TiXmlText *tmpText; TiXmlNode *child = 0; for( child = ar->FirstChild(); child; child = child->NextSibling() ) { // std::string text = child->Value(); // std::cout << "<k>" << text.c_str() << "</k> : " << std::endl; if (child->Type() == TiXmlNode::ELEMENT) { tmpElement = child->ToElement(); if (tmpElement->ValueStr() == "k") { ++_countXdxfWords; word = tmpElement->GetText(); //get the <k>WORD</k> pptxt::makeUpper(word); //force to UPPER case (def tests against it, below) } //else ignore; dont care about <b> or <c> etc } else if (word.length() && child->Type() == TiXmlNode::TEXT) { tmpText = child->ToText(); def = tmpText->Value(); //get the text (NOT in a <></> tag, wtf? //check if the def starts with the dictionary word. //Some xdxf dictionary defs I've seen do something like: //"abbacy n : the jurisdiction or office of an abbot" //where the "abbacy " part is not required for the game, //as it's already shown so try and remove it. std::string::size_type pos = def.find_first_of(" "); std::string prefix = def.substr(0,pos); //may contain other chars, if so those words will stay pptxt::makeUpper(prefix); if (word == prefix) def = def.substr(pos); if (def.length() > MAX_REWORD_DESCRIPTION) { def.erase(MAX_REWORD_DESCRIPTION); def += "..."; //indicate it was cut short } // std::cout << word.c_str() << " - def: " << tmpstr << std::endl; break; //out of for child loop as we now want next <ar> word and its def } } return ar->NextSiblingElement("ar"); }
void LevelParser::parseTileLayer(TiXmlElement* pTileElement, std::vector<Layer*> *pLayers, const std::vector<Tileset>* pTilesets) { TileLayer* pTileLayer = new TileLayer(m_tileSize, *pTilesets); // tile data std::vector<std::vector<int>> data; std::string decodedIDs; TiXmlElement* pDataNode = NULL; for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { if (e->Value() == std::string("data")) { pDataNode = e; } } for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()) { TiXmlText* text = e->ToText(); std::string t = text->Value(); decodedIDs = base64_decode(t); } // uncompress zlib compression uLongf numGids = m_width * m_height * sizeof(int); std::vector<unsigned> gids(numGids); uncompress((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); std::vector<int> layerRow(m_width); for (int j = 0; j < m_height; j++) { data.push_back(layerRow); } for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width; cols++) { data[rows][cols] = gids[rows * m_width + cols]; } } pTileLayer->setTileIDs(data); pLayers->push_back(pTileLayer); }
/** * Transform a XML node to a StringNode. * * @param xmlElement XML element. * * @return A StringNode. */ StringNode* XmlSettingsTree::xmlToStringNode( TiXmlElement* xmlElement ) { StringNode* retNode = NULL; TiXmlHandle handler( xmlElement ); TiXmlText* textElement = handler.FirstChild().Text(); if( textElement != NULL ) { String value = textElement->Value(); retNode = new StringNode( value ); } return retNode; }
/** * Transform a XML node to a IntegerNode. * * @param xmlElement XML element. * * @return A IntegerNode. */ IntegerNode* XmlSettingsTree::xmlToIntegerNode( TiXmlElement* xmlElement ) { IntegerNode* retNode = NULL; TiXmlHandle handler( xmlElement ); TiXmlText* textElement = handler.FirstChild().Text(); if( textElement != NULL ) { String value = textElement->Value(); retNode = new IntegerNode( TextUtils::stringToInt( value ) ); } return retNode; }
void CKSXML_Read_Project::Set_Temp_Online_Project_Name(TiXmlNode* pParent) { if ( !pParent ) return; TiXmlNode* pChild = pParent->FirstChild(); if ( pChild ){ TiXmlText* pText; pText = pChild->ToText(); msTemp_Online_Project_Name = pText->Value(); } }
const String& MimeType::comment(void) { // calling without mime loaded do nothing if(!(status & MIME_LOADED)) return mcmt; if(status & COMMENT_LOADED) return mcmt; String ttype = mtype; ttype += ".xml"; const char* p = xdg_mime_find_data(ttype.c_str()); if(!p) return mcmt; String path = p; TiXmlDocument doc(path.c_str()); if(!doc.LoadFile()) { E_DEBUG(E_STRLOC ": MimeType::comment() %s malformed\n", path.c_str()); return mcmt; } TiXmlNode* el = doc.FirstChild("mime-type"); /* * First element which does not have "xml:lang" attribute * is default one. So hunt that one :) * * Btw. TinyXML does not handle XML namespaces and will return * "<namespace>:<attribute>" value. This is not big deal as long * as correctly fetch attribute values. */ for(el = el->FirstChildElement(); el; el = el->NextSibling()) { if(strncmp(el->Value(), "comment", 7) == 0) { // TODO: add locale here if(!el->ToElement()->Attribute("xml:lang")) { TiXmlText* data = el->FirstChild()->ToText(); if(data) { mcmt = data->Value(); break; } } } } status |= COMMENT_LOADED; return mcmt; }
/* @method CreateSparse @discussion Create a SparseMatrix, based on the XML attributes. The object is returned by value. @throws KII_invalid_argument @param matElement pointer to Matrix XML element @result The SparseMatrix object. */ SparseMatrix MatrixFactory::CreateSparse(TiXmlElement* matElement) { string type; string init; int rows, columns; FLOAT multiplier; TiXmlHandle matHandle(matElement); GetAttributes(matElement, type, init, rows, columns, multiplier); #ifdef MDEBUG cerr << "Creating SparseMatrix with attributes: " << type << ", " << init << ", " << rows << "X" << columns << ", " << multiplier << endl; #endif if (type == "diag") { if (init == "none") { // a string of values is present & passed TiXmlText* valuesNode = matHandle.FirstChild().Text(); if (valuesNode == NULL) throw KII_invalid_argument("Contents not specified for Sparese Matrix with init='none'."); const char* values = valuesNode->Value(); #ifdef MDEBUG cerr << "\tData present for initialization: " << values << endl; #endif return SparseMatrix(rows, columns, multiplier, values); } else if (init == "const") { // No string of values or XML row data if (multiplier == 0.0) return SparseMatrix(rows, columns); else throw KII_invalid_argument("A sparse matrix can only be initialized to zero with const XML init"); } else throw KII_invalid_argument("Invalid init for sparse matrix"); } else if (type == "sparse") { if (init == "none") // a sequence of row data nodes is present & passed return SparseMatrix(rows, columns, multiplier, matElement); else if (init == "const") { // No row data if (multiplier == 0.0) return SparseMatrix(rows, columns); else throw KII_invalid_argument("A sparse matrix can only be initialized to zero with const XML init"); } else throw KII_invalid_argument("A sparse matrix can only be initialized to zero with const XML init"); } // If we get here, then something is really wrong throw KII_invalid_argument("Invalid type specified for sparse matrix."); }
bool ConfigManager::Read(const wxString& name, ISerializable* object) { wxString str; wxString key(name); TiXmlElement* e = AssertPath(key); TiXmlHandle parentHandle(e); TiXmlText *t = (TiXmlText *) parentHandle.FirstChild(cbU2C(key)).FirstChild("obj").FirstChild().Node(); if (t) { str.assign(cbC2U(t->Value())); object->SerializeIn(wxBase64::Decode(str)); } return wxEmptyString; }
dustring duXmlStatic::GetElementText(TiXmlElement *pElement) { dustring strText = _T(""); TiXmlNode *pChildNode = pElement->FirstChild(); while (pChildNode) { if (pChildNode->Type() == TiXmlNode::TEXT) { TiXmlText *pXmlText = pChildNode->ToText(); strText += pXmlText->Value(); } pChildNode = pChildNode->NextSibling(); } return strText; }
void BulletMLParserTinyXML::getTree(TiXmlNode* node) { if (node->ToComment() != 0) return; translateNode(node); TiXmlNode* child; for (child = node->FirstChild(); child; child = child->NextSibling()) { TiXmlText* text; if ((text = child->ToText()) != 0) { curNode_->setValue(text->Value()); break; } getTree(child); } curNode_ = curNode_->getParent(); }
void SE_UnitHeightHandler::handle(SE_Element* parent, TiXmlElement* xmlElement, unsigned int indent) { SE_TextureCoordAnimation* anim = (SE_TextureCoordAnimation*)parent->getAnimation(); if(anim == NULL) return; TiXmlNode* pChild; TiXmlNode* currNode = xmlElement; for(pChild = currNode->FirstChild() ; pChild != NULL ; pChild = pChild->NextSibling()) { int t = pChild->Type(); if(t != TiXmlNode::TINYXML_TEXT) return; TiXmlText* pText = pChild->ToText(); const char* value = pText->Value(); int h = atoi(value); anim->setUnitHeight(h); } }
// This function creates a VectorMatrix from the given tinyxml Element // and its children. // // Input: // matElement: tinyxml DOM node containing a Matrix element // Postconditions" // If no problems, VectorMatrix object created and // initialized. // Returns: // VectorMatrix object (will be empty if some failure occurs). VectorMatrix MatrixFactory::CreateVector(TiXmlElement* matElement) { string type; string init; int rows, columns; FLOAT multiplier; string values; TiXmlHandle matHandle(matElement); GetAttributes(matElement, type, init, rows, columns, multiplier); #ifdef VDEBUG cerr << "Creating Vector with attributes: " << type << ", " << init << ", " << rows << "X" << columns << ", " << multiplier << endl; #endif // Get the Text node that contains the matrix values, if needed if (init == "none") { TiXmlText* valuesNode = matHandle.FirstChild().Text(); if (valuesNode == NULL) throw KII_invalid_argument("Contents not specified for Vector with init='none'."); values = valuesNode->Value(); #ifdef VDEBUG cerr << "\tData present for initialization: " << values << endl; #endif } else if (init == "implementation") throw KII_invalid_argument("MatrixFactory cannot create implementation-dependent Matrices; client program must perform creation"); if (type == "sparse") throw KII_invalid_argument("Sparse matrix requested in XML but CreateVector called"); if ((type == "complete") || (type == "diag")) { if ((rows > 1) && (columns > 1)) // Create a 2D Matrix throw KII_domain_error("Cannot create Vector with more than one dimension."); else // Create a 1D Matrix return VectorMatrix(type, init, rows, columns, multiplier, values); } else if (type == "sparse") throw KII_invalid_argument("No such thing as sparse Vectors"); else throw KII_invalid_argument("Illegal Vector type"); return VectorMatrix(); }
void CKSXML_Read_Project::Read_Sample_Object(TiXmlElement* pElement) { if ( !pElement ) return ; TiXmlAttribute* pAttrib = pElement->FirstAttribute(); CSample_Data Sample_Data; // set sample uuid if(pAttrib) { std::string sUUID = pAttrib->Value(); Sample_Data.Set_UUID(sUUID); } TiXmlNode* pChild; TiXmlText* pText; for ( pChild = pElement->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if(pChild->Type() == TiXmlNode::ELEMENT){ if (stricmp("name", pChild->Value()) == 0) { TiXmlNode* pName = pChild->FirstChild(); if(pName) { pText = pName->ToText(); if(pText) Sample_Data.Name(pText->Value()); } } else if (stricmp("take", pChild->Value()) == 0) { CTake_Data* pTake_Data = Sample_Data.Get_Take_Data(); // set take name pTake_Data->Screen_Name( Sample_Data.Name() ); Read_Take_Object(pChild->ToElement(), pTake_Data); } } } // store sample data in list mSample_Data_List.push_back(Sample_Data); }
void processNode(XmlElement* parent, TiXmlNode* node) { XmlElement* new_element = 0; switch (node->Type()) { case TiXmlNode::TINYXML_ELEMENT: { TiXmlElement* element = node->ToElement(); std::string tag = element->Value(); std::transform( tag.begin(), tag.end(), tag.begin(), tolower); //Get all the attributes XmlAttributes attrs; TiXmlAttribute* attr = element->FirstAttribute(); while (attr) { std::string name = attr->Name(); std::string value = attr->Value(); std::transform( name.begin(), name.end(), name.begin(), tolower); attrs[name] = value; attr = attr->Next(); } //All the element to the stack new_element = new XmlElement( tag, attrs ); parent->getChildren().push_back( new_element ); } break; case TiXmlNode::TINYXML_TEXT: { TiXmlText* text = node->ToText(); std::string data( text->Value()); parent->getChildren().push_back( new XmlText( data ) ); } break; } XmlElement* new_parent = new_element ? new_element : parent; TiXmlNode* child; for (child = node->FirstChild(); child != 0; child = child->NextSibling()) { processNode( new_parent, child ); } }
/** Return the list of note of the given player * * \param playerName the player's name. * * \return a pointer to a tNoteList STL list. */ tNoteList* RainbruRPG::Network::Ident::xmlAccountList::getAccountNoteList( const char* playerName){ tNoteList* list=new tNoteList(); TiXmlText* textNode; const char* nodeName; tNoteListItem* i1; TiXmlHandle docHandle( doc ); TiXmlElement* child = docHandle.FirstChild( "PlayerList" ) .FirstChild( "Player" ).Element(); for( child; child; child=child->NextSiblingElement() ){ nodeName= getXMLTextFromName(child, "Name"); if (strcmp( playerName, nodeName )==0){ TiXmlHandle docHandle( child ); TiXmlElement* noteChild = docHandle.FirstChild( "Note" ).Element(); for( noteChild; noteChild; noteChild=noteChild->NextSiblingElement() ){ i1=new tNoteListItem(); i1->title=noteChild->Attribute("title"); // Cause a segfault if omitted if (noteChild->FirstChild()){ textNode=noteChild->FirstChild()->ToText(); if (textNode) i1->text=textNode->Value(); else LOGI(_("A note has no text")); } else LOGI(_("A note element has no child")); list->push_back(i1); } } } return list; }
bool populateBag(TiXmlNode* pParent) { if ( !pParent ) return false; TiXmlNode* pChild; TiXmlText* pText; int t = pParent->Type(); switch ( t ) { case TiXmlNode::ELEMENT: // notify start of new element this->startElement( pParent->Value(), pParent->ToElement()->FirstAttribute() ); // recurse in children, if any for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { if ( this->populateBag( pChild ) == false) return false; } // notify end of element if ( this->endElement() == false ) return false; break; case TiXmlNode::TEXT: pText = pParent->ToText(); this->characters( pText->Value() ); break; // not interested in these... case TiXmlNode::DECLARATION: case TiXmlNode::COMMENT: case TiXmlNode::UNKNOWN: case TiXmlNode::DOCUMENT: default: break; } return true; }
const char* SimXMLDocument::getText() { if(m_paNode.empty()) return ""; const int iFinalElement = m_paNode.size() - 1; TiXmlNode* pNode = m_paNode[iFinalElement]; if(!pNode) return ""; if (pNode->FirstChild() != NULL) { TiXmlText* text = pNode->FirstChild()->ToText(); if (!text) return ""; return text->Value(); } else return ""; }
const char* SimXMLDocument::getData() { if(m_paNode.empty()) return ""; const int iFinalElement = m_paNode.size() - 1; TiXmlNode* pNode = m_paNode[iFinalElement]; if(!pNode) return ""; TiXmlNode * firstChild = pNode->FirstChild(); if(!firstChild) return ""; TiXmlText* text = firstChild->ToText(); if( !text ) return ""; return text->Value(); }
TiXmlText* PluginXmlParser::requireText ( const TiXmlElement& elem, OsStatus* err) { TiXmlNode* tn = (TiXmlNode*)elem.FirstChild(); if (tn != NULL && tn->Type() == TiXmlNode::TEXT) { TiXmlText* t = tn->ToText(); if (t->Value() != NULL) { return t; } } OsSysLog::add(FAC_SIP, PRI_ERR, "PluginXmlParser::requiredText " "missing element text body %s ", elem.Value()); *err = OS_FAILED; return NULL; }
bool CSiteManager::GetBookmarks(wxString sitePath, std::list<wxString> &bookmarks) { wxChar c = sitePath[0]; if (c != '0' && c != '1') return false; sitePath = sitePath.Mid(1); // We have to synchronize access to sitemanager.xml so that multiple processed don't write // to the same file or one is reading while the other one writes. CInterProcessMutex mutex(MUTEX_SITEMANAGER); CXmlFile file; TiXmlElement* pDocument = 0; if (c == '0') pDocument = file.Load(_T("sitemanager")); else { const wxString& defaultsDir = wxGetApp().GetDefaultsDir(); if (defaultsDir == _T("")) return false; pDocument = file.Load(wxFileName(defaultsDir, _T("fzdefaults.xml"))); } if (!pDocument) { wxMessageBox(file.GetError(), _("Error loading xml file"), wxICON_ERROR); return false; } TiXmlElement* pElement = pDocument->FirstChildElement("Servers"); if (!pElement) return false; std::list<wxString> segments; if (!UnescapeSitePath(sitePath, segments)) { wxMessageBox(_("Site path is malformed."), _("Invalid site path")); return 0; } TiXmlElement* pChild = GetElementByPath(pElement, segments); if (pChild && !strcmp(pChild->Value(), "Bookmark")) pChild = pChild->Parent()->ToElement(); if (!pChild || strcmp(pChild->Value(), "Server")) return 0; // Bookmarks for (TiXmlElement* pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark")) { TiXmlHandle handle(pBookmark); wxString name = GetTextElement_Trimmed(pBookmark, "Name"); if (name.empty()) continue; wxString localPath; CServerPath remotePath; TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text(); if (localDir) localPath = ConvLocal(localDir->Value()); TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text(); if (remoteDir) remotePath.SetSafePath(ConvLocal(remoteDir->Value())); if (localPath.empty() && remotePath.IsEmpty()) continue; bookmarks.push_back(name); } return true; }
int CCrashInfoReader::ParseCrashDescription(CString sFileName, BOOL bParseFileItems, CErrorReportInfo& eri) { strconv_t strconv; FILE* f = NULL; #if _MSC_VER<1400 f = _tfopen(sFileName, _T("rb")); #else _tfopen_s(&f, sFileName, _T("rb")); #endif if(f==NULL) return 1; TiXmlDocument doc; bool bOpen = doc.LoadFile(f); if(!bOpen) return 1; TiXmlHandle hRoot = doc.FirstChild("CrashRpt"); if(hRoot.ToElement()==NULL) { fclose(f); return 1; } { TiXmlHandle hCrashGUID = hRoot.FirstChild("CrashGUID"); if(hCrashGUID.ToElement()!=NULL) { if(hCrashGUID.FirstChild().ToText()!=NULL) { const char* szCrashGUID = hCrashGUID.FirstChild().ToText()->Value(); if(szCrashGUID!=NULL) eri.m_sCrashGUID = strconv.utf82t(szCrashGUID); } } } { TiXmlHandle hAppName = hRoot.FirstChild("AppName"); if(hAppName.ToElement()!=NULL) { const char* szAppName = hAppName.FirstChild().ToText()->Value(); if(szAppName!=NULL) eri.m_sAppName = strconv.utf82t(szAppName); } } { TiXmlHandle hAppVersion = hRoot.FirstChild("AppVersion"); if(hAppVersion.ToElement()!=NULL) { TiXmlText* pText = hAppVersion.FirstChild().ToText(); if(pText!=NULL) { const char* szAppVersion = pText->Value(); if(szAppVersion!=NULL) eri.m_sAppVersion = strconv.utf82t(szAppVersion); } } } { TiXmlHandle hImageName = hRoot.FirstChild("ImageName"); if(hImageName.ToElement()!=NULL) { TiXmlText* pText = hImageName.FirstChild().ToText(); if(pText!=NULL) { const char* szImageName = pText->Value(); if(szImageName!=NULL) eri.m_sImageName = strconv.utf82t(szImageName); } } } { TiXmlHandle hSystemTimeUTC = hRoot.FirstChild("SystemTimeUTC"); if(hSystemTimeUTC.ToElement()!=NULL) { TiXmlText* pText = hSystemTimeUTC.FirstChild().ToText(); if(pText!=NULL) { const char* szSystemTimeUTC = pText->Value(); if(szSystemTimeUTC!=NULL) eri.m_sSystemTimeUTC = strconv.utf82t(szSystemTimeUTC); } } } if(bParseFileItems) { // Get directory name CString sReportDir = sFileName; int pos = sFileName.ReverseFind('\\'); if(pos>=0) sReportDir = sFileName.Left(pos); if(sReportDir.Right(1)!=_T("\\")) sReportDir += _T("\\"); TiXmlHandle fl = hRoot.FirstChild("FileList"); if(fl.ToElement()==0) { fclose(f); return 1; } TiXmlHandle fi = fl.FirstChild("FileItem"); while(fi.ToElement()!=0) { const char* pszDestFile = fi.ToElement()->Attribute("name"); const char* pszDesc = fi.ToElement()->Attribute("description"); const char* pszOptional = fi.ToElement()->Attribute("optional"); if(pszDestFile!=NULL) { CString sDestFile = strconv.utf82t(pszDestFile); ERIFileItem item; item.m_sDestFile = sDestFile; item.m_sSrcFile = sReportDir + sDestFile; if(pszDesc) item.m_sDesc = strconv.utf82t(pszDesc); item.m_bMakeCopy = FALSE; if(pszOptional && strcmp(pszOptional, "1")==0) item.m_bAllowDelete = true; // Check that file really exists DWORD dwAttrs = GetFileAttributes(item.m_sSrcFile); if(dwAttrs!=INVALID_FILE_ATTRIBUTES && (dwAttrs&FILE_ATTRIBUTE_DIRECTORY)==0) { eri.m_FileItems[sDestFile] = item; } } fi = fi.ToElement()->NextSibling("FileItem"); } } fclose(f); return 0; }
CSiteManagerItemData_Site* CSiteManager::GetSiteByPath(wxString sitePath) { wxChar c = sitePath[0]; if (c != '0' && c != '1') { wxMessageBox(_("Site path has to begin with 0 or 1."), _("Invalid site path")); return 0; } sitePath = sitePath.Mid(1); // We have to synchronize access to sitemanager.xml so that multiple processed don't write // to the same file or one is reading while the other one writes. CInterProcessMutex mutex(MUTEX_SITEMANAGER); CXmlFile file; TiXmlElement* pDocument = 0; if (c == '0') pDocument = file.Load(_T("sitemanager")); else { const wxString& defaultsDir = wxGetApp().GetDefaultsDir(); if (defaultsDir == _T("")) { wxMessageBox(_("Site does not exist."), _("Invalid site path")); return 0; } wxFileName name(defaultsDir, _T("fzdefaults.xml")); pDocument = file.Load(name); } if (!pDocument) { wxMessageBox(file.GetError(), _("Error loading xml file"), wxICON_ERROR); return 0; } TiXmlElement* pElement = pDocument->FirstChildElement("Servers"); if (!pElement) { wxMessageBox(_("Site does not exist."), _("Invalid site path")); return 0; } std::list<wxString> segments; if (!UnescapeSitePath(sitePath, segments) || segments.empty()) { wxMessageBox(_("Site path is malformed."), _("Invalid site path")); return 0; } TiXmlElement* pChild = GetElementByPath(pElement, segments); if (!pChild) { wxMessageBox(_("Site does not exist."), _("Invalid site path")); return 0; } TiXmlElement* pBookmark; if (!strcmp(pChild->Value(), "Bookmark")) { pBookmark = pChild; pChild = pChild->Parent()->ToElement(); segments.pop_back(); } else pBookmark = 0; CSiteManagerItemData_Site* data = ReadServerElement(pChild); if (!data) { wxMessageBox(_("Could not read server item."), _("Invalid site path")); return 0; } if (pBookmark) { TiXmlHandle handle(pBookmark); wxString localPath; CServerPath remotePath; TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text(); if (localDir) localPath = ConvLocal(localDir->Value()); TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text(); if (remoteDir) remotePath.SetSafePath(ConvLocal(remoteDir->Value())); if (!localPath.empty() && !remotePath.IsEmpty()) { data->m_sync = GetTextElementBool(pBookmark, "SyncBrowsing", false); } else data->m_sync = false; data->m_localDir = localPath; data->m_remoteDir = remotePath; } data->m_path = BuildPath( c, segments ); return data; }
bool CSiteManager::Load(TiXmlElement *pElement, CSiteManagerXmlHandler* pHandler) { wxASSERT(pElement); wxASSERT(pHandler); for (TiXmlElement* pChild = pElement->FirstChildElement(); pChild; pChild = pChild->NextSiblingElement()) { if (!strcmp(pChild->Value(), "Folder")) { wxString name = GetTextElement_Trimmed(pChild); if (name.empty()) continue; const bool expand = GetTextAttribute(pChild, "expanded") != _T("0"); if (!pHandler->AddFolder(name, expand)) return false; Load(pChild, pHandler); if (!pHandler->LevelUp()) return false; } else if (!strcmp(pChild->Value(), "Server")) { CSiteManagerItemData_Site* data = ReadServerElement(pChild); if (data) { pHandler->AddSite(data); // Bookmarks for (TiXmlElement* pBookmark = pChild->FirstChildElement("Bookmark"); pBookmark; pBookmark = pBookmark->NextSiblingElement("Bookmark")) { TiXmlHandle handle(pBookmark); wxString name = GetTextElement_Trimmed(pBookmark, "Name"); if (name.empty()) continue; CSiteManagerItemData* data = new CSiteManagerItemData(CSiteManagerItemData::BOOKMARK); TiXmlText* localDir = handle.FirstChildElement("LocalDir").FirstChild().Text(); if (localDir) data->m_localDir = GetTextElement(pBookmark, "LocalDir"); TiXmlText* remoteDir = handle.FirstChildElement("RemoteDir").FirstChild().Text(); if (remoteDir) data->m_remoteDir.SetSafePath(ConvLocal(remoteDir->Value())); if (data->m_localDir.empty() && data->m_remoteDir.IsEmpty()) { delete data; continue; } if (!data->m_localDir.empty() && !data->m_remoteDir.IsEmpty()) data->m_sync = GetTextElementBool(pBookmark, "SyncBrowsing", false); pHandler->AddBookmark(name, data); } if (!pHandler->LevelUp()) return false; } } } return true; }
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; }
string ProRataConfig::getValue( TiXmlDocument &txdDoc, const vector<string> &vsTagList ) { // Check to see if the provided XML node is valid. // If yes, extract the value from the node return it. // If no, return emply string. // creat a pointer to a node TiXmlNode * txnTemp = NULL; // check if the tree path is not empty if ( vsTagList.size() < 1 ) return string(""); // iterator for the input vsTagList vector<string>::const_iterator itrTagListItr; itrTagListItr = vsTagList.begin(); // move the pointer to txddoc's first child with the specified tag name txnTemp = txdDoc.FirstChild( (*itrTagListItr ).c_str() ); // check if this element exists if ( ! txnTemp ) { cout << "ERROR: TAG\"" << (*itrTagListItr) << "\" not found in the configuration file." << endl; return string(""); } itrTagListItr++; // move the pointer down the hierarchial tree of elements for( ; itrTagListItr != vsTagList.end(); itrTagListItr++ ) { txnTemp = txnTemp->FirstChild( (*itrTagListItr ).c_str() ); if ( ! txnTemp ) { cout << "ERROR: TAG\"" << (*itrTagListItr) << "\" not found in the configuration file." << endl; return string(""); } } // move the iterator back to point it to the last element name itrTagListItr--; /* * inside the pointed element, there could be a mixture of * text nodes, comment nodes and element nodes * loop thru every nodes and for each text nodes, retrieve their text * concatenate the text together and return them */ TiXmlText *txs; string sTemp = ""; // point txnTemp to the child nodes and loop thru every child node for( txnTemp = txnTemp->FirstChild(); txnTemp; txnTemp = txnTemp->NextSibling() ) { // if this node is pointing to a node of type TEXT, which equals 4 in enum NodeType if( txnTemp->Type() == 4 ) { // cast txnTemp to a text node txs = txnTemp->ToText(); // get txnTemp's value and then append it to sTemp if( txs ) sTemp.append( txs->Value() ); } } return sTemp; }
bool NetworkSystem::create( const string& config ){ TiXmlDocument doc( config.c_str() ); if ( !doc.LoadFile() ){ return false; } //create PEER mPeer = RakNetworkFactory::GetRakPeerInterface(); //create RPC3 mRPC3 = new RakNet::RPC3(); //create Network ID manager mNetworkIDManager = new NetworkIDManager(); TiXmlDocument * document = doc.GetDocument(); TiXmlHandle docHandle ( document ); //check if server TiXmlElement * server = docHandle.FirstChildElement("server").Element(); if ( server ){ mType = NetworkSystem::Server; int mMaxConnections; if ( !server->Attribute("connections",&mMaxConnections) ){ cerr << "missing 'connections' attribute in 'server' tag" << endl; destroy(); return false; } vector<SocketDescriptor> interfaces; //loop over interfaces for( TiXmlElement * child = docHandle.FirstChildElement("server").FirstChildElement("interface").Element(); child; child = child->NextSiblingElement("interface") ) { if ( child ){ TiXmlHandle ifacehandle ( child ); TiXmlText * ip = ifacehandle.FirstChild("ip").FirstChild().Text(); TiXmlText * port = ifacehandle.FirstChild("port").FirstChild().Text(); if ( ip && port ){ SocketDescriptor sd; memcpy(sd.hostAddress,ip->Value(), sizeof(char) * 32); sd.port = atoi(port->Value()); interfaces.push_back(sd); } } } if ( interfaces.empty() ){ cerr << "no 'interfaces' specified in 'server' tag" << endl; destroy(); return false; } //copy SocketDescriptor * mSocketDescriptions = new SocketDescriptor[interfaces.size()]; for ( unsigned int i = 0; i < interfaces.size(); i++ ){ mSocketDescriptions[i] = interfaces[i]; } mNetworkIDManager->SetIsNetworkIDAuthority(true); mRPC3->SetNetworkIDManager(mNetworkIDManager); //start server mPeer->Startup(mMaxConnections,30, mSocketDescriptions, interfaces.size()); delete [] mSocketDescriptions; } else { //check for client tag (should be there) TiXmlElement * client = docHandle.FirstChildElement("client").Element(); if ( client ){ mType = NetworkSystem::Client; mRPC3->SetNetworkIDManager(mNetworkIDManager); //mPeer->Connect("",0,0,0); } else { cerr << "no 'server' or 'client' tag" << endl; destroy(); return false; } } //attach RPC mPeer->AttachPlugin(mRPC3); return true; }