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; }
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" ); doc.Print( stdout ); TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChildElement(); // This skips the "PDA" comment. assert( node ); itemElement = node->ToElement(); assert( itemElement ); itemElement->SetAttribute( "priority", 2 ); // Change the distance to "doing bills" from // "none" to "here". It's the next sibling element. itemElement = itemElement->NextSiblingElement(); assert( itemElement ); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil 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(); 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 doc; doc.Parse( error ); XmlTest( "Error row", doc.ErrorRow(), 3 ); XmlTest( "Error column", doc.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" " <!-- Silly example -->\n" " <door wall='north'>A great door!</door>\n" "\t<door wall='east'/>" "</room>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild(); TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild(); TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 ); TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 ); assert( docHandle.Node() ); assert( roomHandle.Element() ); assert( commentHandle.Node() ); assert( textHandle.Text() ); assert( door0Handle.Element() ); assert( door1Handle.Element() ); TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration(); assert( declaration ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); TiXmlText* text = textHandle.Text(); TiXmlComment* comment = commentHandle.Node()->ToComment(); assert( comment ); TiXmlElement* door0 = door0Handle.Element(); TiXmlElement* door1 = door1Handle.Element(); XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 ); XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 ); XmlTest( "Location tracking: room row", room->Row(), 1 ); XmlTest( "Location tracking: room col", room->Column(), 45 ); XmlTest( "Location tracking: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: doors col", doors->Column(), 51 ); XmlTest( "Location tracking: Comment row", comment->Row(), 2 ); XmlTest( "Location tracking: Comment col", comment->Column(), 3 ); XmlTest( "Location tracking: text row", text->Row(), 3 ); XmlTest( "Location tracking: text col", text->Column(), 24 ); XmlTest( "Location tracking: door0 row", door0->Row(), 3 ); XmlTest( "Location tracking: door0 col", door0->Column(), 5 ); XmlTest( "Location tracking: door1 row", door1->Row(), 4 ); XmlTest( "Location tracking: door1 col", door1->Column(), 5 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" "</room>"; TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); assert( docHandle.Node() ); assert( roomHandle.Element() ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 ); XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 ); XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 ); } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); XmlTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE ); } #ifdef TIXML_USE_STL { ////////////////////////////////////////////////////// cout << "\n** Streaming. **\n"; // Round trip check: stream in, then stream back out to verify. The stream // out has already been checked, above. We use the output istringstream inputStringStream( outputStream.str() ); TiXmlDocument document0; inputStringStream >> document0; ostringstream outputStream0( ostringstream::out ); outputStream0 << document0; XmlTest( "Stream round trip correct.", string( demoEnd ).c_str(), outputStream0.str().c_str(), true ); std::string str; str << document0; XmlTest( "String printing correct.", string( demoEnd ).c_str(), str.c_str(), true ); } #endif // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "utf8testout.xml", "r" ); FILE* verify = fopen( "utf8testverify.xml", "r" ); if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); if ( strcmp( verifyBuf, savedBuf ) ) { okay = 0; break; } } fclose( saved ); fclose( verify ); } XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else 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 ); } ////////////////////////////////////////////////////// printf( "\n** Fuzzing **\n" ); const int FUZZ_ITERATION = 300; // The only goal is not to crash on bad input. int len = 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 ("\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.", 0, (int)doc.Error() ); // not an error to tinyxml XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<ä>" "CöntäntßäöüÄÖÜ" "</ä>"; TiXmlDocument doc; doc.Parse( str ); //doc.Print( stdout, 0 ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() ); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // 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' />" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; float f; bool b; 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", (d==3.0), true ); XmlTest( "QueryValueAttribute", (i==3), true ); XmlTest( "QueryValueAttribute", (f==3.0f), 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 ); } /* 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; }
TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { TiXmlNode* returnNode = 0; p = SkipWhiteSpace( p, encoding ); if( !p || !*p || *p != '<' ) { return 0; } TiXmlDocument* doc = GetDocument(); p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) { return 0; } // What is this thing? // - Elements start with a letter or underscore, but xml is reserved. // - Comments: <!-- // - Decleration: <?xml // - Everthing else is unknown to tinyxml. // const char* xmlHeader = { "<?xml" }; const char* commentHeader = { "<!--" }; const char* dtdHeader = { "<!" }; const char* cdataHeader = { "<![CDATA[" }; if ( StringEqual( p, xmlHeader, true, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Declaration\n" ); #endif returnNode = XNEW(TiXmlDeclaration)(); //new TiXmlDeclaration(); } else if ( StringEqual( p, commentHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Comment\n" ); #endif returnNode = XNEW(TiXmlComment)(); //new TiXmlComment(); } else if ( StringEqual( p, cdataHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing CDATA\n" ); #endif TiXmlText* text = XNEW(TiXmlText)(""); //new TiXmlText( "" ); text->SetCDATA( true ); returnNode = text; } else if ( StringEqual( p, dtdHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Unknown(1)\n" ); #endif returnNode = XNEW(TiXmlUnknown)(); //new TiXmlUnknown(); } else if ( IsAlpha( *(p+1), encoding ) || *(p+1) == '_' ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Element\n" ); #endif returnNode = XNEW(TiXmlElement)(""); //new TiXmlElement( "" ); } else { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Unknown(2)\n" ); #endif returnNode = XNEW(TiXmlUnknown)(); //new TiXmlUnknown(); } if ( returnNode ) { // Set the parent, so it can report errors returnNode->parent = this; } else { if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } return returnNode; }
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 \n data -->" "<ToDo>\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'> Look for Evil Dinosaurs! </Item>" "</ToDo>"; /* What the todo list should look like after processing. <?xml version="1.0" standalone="no" ?> <!-- Our to do list data --> <ToDo> <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="Voo" position="counselor" /> </Meeting> <Meeting where="Lunch" /> </Item> <Item priority="2" distance="here"> Do bills </Item> </ToDo> */ // The example parses from the character string (above): { // 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().c_str(), doc.ErrorDesc().c_str() ); exit( 1 ); } doc.SaveFile(); } TiXmlDocument doc( "demotest.xml" ); doc.LoadFile(); printf( "** Demo doc read from disk: ** \n\n" ); doc.Print( stdout ); TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChild(); 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(); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil Dinosours!" item. // It is 1 more sibling away. We ask the parent to remove // a particular child. itemElement = itemElement->NextSiblingElement(); todoElement->RemoveChild( itemElement ); itemElement = 0; // -------------------------------------------------------- // What follows is an example of created elements and text // nodes and adding them to the document. // -------------------------------------------------------- // Add some meetings. TiXmlElement item( "Item" ); item.SetAttribute( "priority", "1" ); item.SetAttribute( "distance", "far" ); TiXmlText text; text.SetValue( "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", "Voo" ); 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 ); // -------------------------------------------------------- // Different ways to walk the XML document. // -------------------------------------------------------- int count = 0; TiXmlElement* element; // Walk all the top level nodes of the document. count = 0; for( node = doc.FirstChild(); node; node = node->NextSibling() ) { count++; } printf( "The document contains %d top level nodes. (3)\n", count ); // Walk all the top level nodes of the document, // using a different sytax. count = 0; for( node = doc.IterateChildren( 0 ); node; node = doc.IterateChildren( node ) ) { count++; } printf( "The document contains %d top level nodes. (3)\n", count ); // Walk all the elements in a node. count = 0; for( element = todoElement->FirstChildElement(); element; element = element->NextSiblingElement() ) { count++; } printf( "The 'ToDo' element contains %d elements. (3)\n", count ); // Walk all the elements in a node by value. count = 0; for( node = todoElement->FirstChild( "Item" ); node; node = node->NextSibling( "Item" ) ) { count++; } printf( "The 'ToDo' element contains %d nodes with the value of 'Item'. (3)\n", count ); /* for( int i=0; i<1000; i++ ) doc.LoadFile( "SmallRuleset1.xml" ); doc.SaveFile( "smalltest.xml" ); */ return 0; }
OsStatus ForwardRules::parseRouteMatchContainer(const Url& requestUri, const SipMessage& request, UtlString& routeToString, UtlString& mappingType, bool& authRequired, TiXmlNode* routesNode, TiXmlNode* previousRouteMatchNode) { UtlString testHost; requestUri.getHostAddress(testHost); int testPort = requestUri.getHostPort(); if(testPort == SIP_PORT) { testPort = PORT_NONE; } UtlBoolean routeMatchFound = false; OsStatus methodMatchFound = OS_FAILED; TiXmlElement* routesElement = routesNode->ToElement(); TiXmlNode* routeMatchNode = previousRouteMatchNode; // Iterate through routes container children looking for // route tags while ( (routeMatchNode = routesElement->IterateChildren(routeMatchNode)) && methodMatchFound != OS_SUCCESS) { // Skip non-elements if(routeMatchNode && routeMatchNode->Type() != TiXmlNode::ELEMENT) { continue; } // Skip non-route elements TiXmlElement* routeMatchElement = routeMatchNode->ToElement(); UtlString tagValue = routeMatchElement->Value(); if(tagValue.compareTo(XML_TAG_ROUTEMATCH) != 0 ) { continue; } mappingType.remove(0); routeToString.remove(0); const char* mappingTypePtr = routeMatchElement->Attribute(XML_ATT_MAPPINGTYPE); //get the mapping Type attribute mappingType.append(mappingTypePtr ? mappingTypePtr : ""); // Iterate through the route container's children looking // for routeFrom, routeIPv4subnet, or routeDnsWildcard elements TiXmlNode* routeFromPatternNode = NULL; for( routeFromPatternNode = routeMatchElement->FirstChildElement(); routeFromPatternNode; routeFromPatternNode = routeFromPatternNode->NextSiblingElement() ) { // Skip elements that aren't of the "domainMatches" family enum {ret_from, ret_ip, ret_dns} routeElementType ; const char *name = routeFromPatternNode->Value() ; if (strcmp(name, XML_TAG_ROUTEFROM) == 0) { routeElementType = ret_from; } else if (strcmp(name, XML_TAG_ROUTEIPV4SUBNET) == 0) { routeElementType = ret_ip; } else if (strcmp(name, XML_TAG_ROUTEDNSWILDCARD) == 0) { routeElementType = ret_dns; } else { continue ; } //found "domainMatches" pattern tag TiXmlElement* routeFromPatternElement = routeFromPatternNode->ToElement(); //get the text value from it TiXmlNode* routeFromPatternText = routeFromPatternElement->FirstChild(); if(routeFromPatternText && routeFromPatternText->Type() == TiXmlNode::TEXT) { TiXmlText* Xmlpattern = routeFromPatternText->ToText(); if (Xmlpattern) { UtlString pattern = Xmlpattern->Value(); switch(routeElementType) { case ret_from: // a routeFrom element matches host and port { Url xmlUrl(pattern.data()); UtlString xmlHost; xmlUrl.getHostAddress(xmlHost); int xmlPort = xmlUrl.getHostPort(); // See if the host and port of the routeFrom elelment // match that of the URI if( (xmlHost.compareTo(testHost, UtlString::ignoreCase) == 0) && ((xmlPort == SIP_PORT && testPort == PORT_NONE) || xmlPort == testPort) ) { routeMatchFound = true; Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "ForwardRules::parseRouteMatchContainer - routeFrom %s matches %s", testHost.data(), pattern.data()); } } break ; case ret_ip: // a routeIPv4subnet matches if the subnet does { // "pattern" is a subnet in CIDR notation (x.y.z.q/size) // "testHost is supposed to be an IPv4 dotted quad routeMatchFound = mPatterns-> IPv4subnet(testHost, pattern); } break ; case ret_dns: // a routeDnsWildcard matches if the domain name does { // "pattern" is a wildcard DNS (*.pingtel.com) // "testHost is a FQDN routeMatchFound = mPatterns-> DnsWildcard(testHost, pattern); } break ; } if (routeMatchFound) { previousRouteMatchNode = routeMatchNode; // Find a match to the request method and recurse // to find child element field(s) matches and // get the routeTo value methodMatchFound = parseMethodMatchContainer(request, routeToString, authRequired, routeMatchNode); if( methodMatchFound == OS_SUCCESS) break; } } } } } return methodMatchFound; }
const char* TiXmlDocument::Parse ( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) { ClearError(); // Parse away, at the document level. Since a document // contains nothing but other tags, most of what happens // here is skipping white space. // sherm 100319: I changed this so that untagged top-level text is // parsed as a Text node rather than a parsing error. CDATA text was // already allowed at the top level so this seems more consistent. if ( !p || !*p ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } // Note that, for a document, this needs to come // before the while space skip, so that parsing // starts from the pointer we are given. location.Clear(); if ( prevData ) { location.row = prevData->cursor.row; location.col = prevData->cursor.col; } else { location.row = 0; location.col = 0; } TiXmlParsingData data( p, TabSize(), location.row, location.col ); location = data.Cursor(); if ( encoding == TIXML_ENCODING_UNKNOWN ) { // Check for the Microsoft UTF-8 lead bytes. const unsigned char* pU = (const unsigned char*)p; if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) { encoding = TIXML_ENCODING_UTF8; useMicrosoftBOM = true; } } // Remember the start of white space in case we end up reading a text // element in a "keep white space" mode. const char* pWithWhiteSpace = p; p = SkipWhiteSpace( p, encoding ); if ( !p ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } // sherm 100319: ignore all but the first Declaration bool haveSeenDeclaration = false; while ( p && *p ) { TiXmlNode* node = 0; if ( *p != '<' ) { // sherm 100319: I added this case by stealing the code from // Element parsing; see above comment. // Take what we have, make a text element. TiXmlText* textNode = new TiXmlText( "" ); if ( !textNode ) { SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding ); return 0; } if ( TiXmlBase::IsWhiteSpaceCondensed() ) { p = textNode->Parse( p, &data, encoding ); } else { // Special case: we want to keep the white space // so that leading spaces aren't removed. p = textNode->Parse( pWithWhiteSpace, &data, encoding ); } if ( !textNode->Blank() ) { LinkEndChild( textNode ); node = textNode; } else delete textNode; } else // We saw a '<', now identify what kind of tag it is. { TiXmlNode* node = Identify( p, encoding ); if ( node ) { p = node->Parse( p, &data, encoding ); if (node->ToDeclaration()) { if (haveSeenDeclaration) { delete node; node=0; // ignore duplicate Declaration } else haveSeenDeclaration = true; } if (node) LinkEndChild( node ); } else { // If Identify fails then no further parsing is possible. break; } } // Did we get encoding info? if ( encoding == TIXML_ENCODING_UNKNOWN && node && node->ToDeclaration() ) { TiXmlDeclaration* dec = node->ToDeclaration(); const char* enc = dec->Encoding(); assert( enc ); if ( *enc == 0 ) encoding = TIXML_ENCODING_UTF8; else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) encoding = TIXML_ENCODING_UTF8; else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice else encoding = TIXML_ENCODING_LEGACY; } pWithWhiteSpace = p; p = SkipWhiteSpace( p, encoding ); } // Was this empty? if ( !firstChild ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); return 0; } // All is well. return p; }
void NivelParser::parseCapaTile(TiXmlElement* pTileElement, std::vector<Capa*> *pCapas, const std::vector<ConjuntoTiles>* pConjuntoTiles, std::vector<CapaTile*> *pCapasDeColision) { CapaTile* pCapaTile = new CapaTile(magnitudTile, *pConjuntoTiles); bool collidable = false; // tile data 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); } // uncompress zlib compression uLongf sizeofids = ancho * altura * sizeof(int); std::vector<int> ids(ancho * altura); uncompress((Bytef*)&ids[0], &sizeofids,(const Bytef*)decodedIDs.c_str(), decodedIDs.size()); std::vector<int> filaCapa(ancho); for(int j = 0; j < altura; j++) { data.push_back(filaCapa); } for(int rows = 0; rows < altura; rows++) { for(int cols = 0; cols < ancho; cols++) { data[rows][cols] = ids[rows * ancho + cols]; } } pCapaTile->setTileIDs(data); //imprimir para corroborar errores //cout<<data.size(); for ( int i = 0; i < data.size(); i++ ) { for ( int j = 0; j < data[i].size(); j++ ) { std::cout << data[i][j] << ' '; } std::cout << std::endl; } pCapaTile->setAnchoMapa(ancho); if(collidable) { pCapasDeColision->push_back(pCapaTile); } pCapas->push_back(pCapaTile); }
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; }
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)) { 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(); } 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; } return data; }
bool ETHEntityProperties::WriteToXMLFile(TiXmlElement *pHeadRoot) const { TiXmlElement *pRoot = new TiXmlElement(GS_L("Entity")); pHeadRoot->LinkEndChild(pRoot); TiXmlElement *pElement; if (emissiveColor != ETH_DEFAULT_EMISSIVE_COLOR) { pElement = new TiXmlElement(GS_L("EmissiveColor")); pRoot->LinkEndChild(pElement); pElement->SetDoubleAttribute(GS_L("r"), emissiveColor.x); pElement->SetDoubleAttribute(GS_L("g"), emissiveColor.y); pElement->SetDoubleAttribute(GS_L("b"), emissiveColor.z); pElement->SetDoubleAttribute(GS_L("a"), emissiveColor.w); } if (spriteCut != ETH_DEFAULT_SPRITE_CUT) { pElement = new TiXmlElement(GS_L("SpriteCut")); pRoot->LinkEndChild(pElement); pElement->SetDoubleAttribute(GS_L("x"), spriteCut.x); pElement->SetDoubleAttribute(GS_L("y"), spriteCut.y); } if (scale != ETH_DEFAULT_SCALE) { pElement = new TiXmlElement(GS_L("Scale")); pRoot->LinkEndChild(pElement); pElement->SetDoubleAttribute(GS_L("x"), scale.x); pElement->SetDoubleAttribute(GS_L("y"), scale.y); } if (pivotAdjust != ETH_DEFAULT_PIVOT_ADJUST) { pElement = new TiXmlElement(GS_L("PivotAdjust")); pRoot->LinkEndChild(pElement); pElement->SetDoubleAttribute(GS_L("x"), pivotAdjust.x); pElement->SetDoubleAttribute(GS_L("y"), pivotAdjust.y); } if (spriteFile != GS_L("")) { pElement = new TiXmlElement(GS_L("Sprite")); pElement->LinkEndChild(new TiXmlText(spriteFile)); pRoot->LinkEndChild(pElement); } if (normalFile != GS_L("")) { pElement = new TiXmlElement(GS_L("Normal")); pElement->LinkEndChild(new TiXmlText(normalFile)); pRoot->LinkEndChild(pElement); } if (glossFile != GS_L("")) { pElement = new TiXmlElement(GS_L("Gloss")); pElement->LinkEndChild(new TiXmlText(glossFile)); pRoot->LinkEndChild(pElement); } if (!particleSystems.empty()) { TiXmlElement *pParticles = new TiXmlElement(GS_L("Particles")); pRoot->LinkEndChild(pParticles); for (unsigned int t=0; t<particleSystems.size(); t++) { if (particleSystems[t]->nParticles > 0) particleSystems[t]->WriteToXMLFile(pParticles); } } if (light) { light->WriteToXMLFile(pRoot); } if (collision) { TiXmlElement *pCollisionRoot = collision->WriteToXMLFile(pRoot); if (pCollisionRoot) { // Write polygon data if (polygon) { pElement = new TiXmlElement(GS_L("Polygon")); TiXmlText* text = new TiXmlText(polygon->GetENMLDeclaration()); text->SetCDATA(true); pElement->LinkEndChild(text); pCollisionRoot->LinkEndChild(pElement); } else if (shape == BS_POLYGON) // it the polygon data is empty, write sample data into it { pElement = new TiXmlElement(GS_L("Polygon")); TiXmlText* text = new TiXmlText(POLYGON_ENML_SAMPLE); text->SetCDATA(true); pElement->LinkEndChild(text); pCollisionRoot->LinkEndChild(pElement); } // Write compound shape data if (compoundShape) { pElement = new TiXmlElement(GS_L("Compound")); TiXmlText* text = new TiXmlText(compoundShape->GetENMLDeclaration()); text->SetCDATA(true); pElement->LinkEndChild(text); pCollisionRoot->LinkEndChild(pElement); } else if (shape == BS_COMPOUND) // it the compound data is empty, write sample data into it { pElement = new TiXmlElement(GS_L("Compound")); TiXmlText* text = new TiXmlText(COMPOUND_SHAPE_ENML_SAMPLE); text->SetCDATA(true); pElement->LinkEndChild(text); pCollisionRoot->LinkEndChild(pElement); } // Write joint data if (enmlJointDefinitions != GS_L("")) { pElement = new TiXmlElement(GS_L("Joints")); pElement->LinkEndChild(new TiXmlText(enmlJointDefinitions)); pCollisionRoot->LinkEndChild(pElement); } } } pRoot->SetAttribute(GS_L("shape"), shape); if (shape != BS_NONE) { pRoot->SetAttribute(GS_L("sensor"), sensor); pRoot->SetAttribute(GS_L("bullet"), bullet); pRoot->SetAttribute(GS_L("fixedRotation"), fixedRotation); pRoot->SetDoubleAttribute(GS_L("friction"), friction); pRoot->SetDoubleAttribute(GS_L("density"), density); pRoot->SetDoubleAttribute(GS_L("restitution"), restitution); pRoot->SetDoubleAttribute(GS_L("gravityScale"), gravityScale); } pRoot->SetAttribute(GS_L("applyLight"), applyLight); if (applyLight) { pRoot->SetDoubleAttribute(GS_L("specularPower"), specularPower); pRoot->SetDoubleAttribute(GS_L("specularBrightness"), specularBrightness); } pRoot->SetAttribute(GS_L("castShadow"), castShadow); if (castShadow) { pRoot->SetDoubleAttribute(GS_L("shadowScale"), shadowScale); pRoot->SetDoubleAttribute(GS_L("shadowLengthScale"), shadowLengthScale); pRoot->SetDoubleAttribute(GS_L("shadowOpacity"), shadowOpacity); } pRoot->SetAttribute(GS_L("type"), type); if (type == ET_LAYERABLE) { pRoot->SetDoubleAttribute(GS_L("layerDepth"), layerDepth); } if (soundVolume != ETH_DEFAULT_SOUND_VOLUME) { pRoot->SetDoubleAttribute(GS_L("soundVolume"), soundVolume); } if (parallaxIntensity != ETH_DEFAULT_PARALLAX_INTENS) { pRoot->SetDoubleAttribute(GS_L("parallaxIntensity"), parallaxIntensity); } if (hideFromSceneEditor != ETH_FALSE) { pRoot->SetAttribute(GS_L("hideFromSceneEditor"), hideFromSceneEditor); } pRoot->SetAttribute(GS_L("static"), staticEntity); pRoot->SetAttribute(GS_L("blendMode"), blendMode); WriteDataToFile(pRoot); return true; }
bool IMContactXMLSerializer1::unserialize(const std::string & data) { TiXmlDocument doc; doc.Parse(data.c_str()); TiXmlHandle docHandle(&doc); TiXmlHandle im = docHandle.FirstChild("im"); // Retrieving associated account EnumIMProtocol::IMProtocol protocol; TiXmlElement * lastChildElt = im.Element(); if (lastChildElt) { protocol = EnumIMProtocol::toIMProtocol(lastChildElt->Attribute("protocol")); } else { return false; } TiXmlText * login = im.FirstChild("account").FirstChild().Text(); if (login) { const IMAccount *imAccount = NULL; std::string loginValue = std::string(login->Value()); //VOXOX - JRT - 2009.04.09 //for (IMAccountList::const_iterator it = _imAccountList.begin(); // it != _imAccountList.end(); // ++it) { // if ((it->getLogin() == loginValue) && // (it->getProtocol() == protocol) ) { // imAccount = &(*it); // } //} imAccount = _imAccountList.findByLoginInfo( loginValue, protocol ); //End VOXOX if (imAccount) { _imContact.setIMAccount(imAccount); } else { LOG_ERROR("this IMAccount does not exist in IMAccountList: " + std::string(login->Value())); return false; } //// } else { _imContact._imAccount = NULL; _imContact._protocol = protocol; } //// //Retrieving contactId TiXmlText * contactId = im.FirstChild("id").FirstChild().Text(); if (contactId) { // wengo or sip account should have a domain // (unfortunately not saved before 2.1rc2... String completeLogin(contactId->Value()); if (!completeLogin.contains("@")) { if (protocol == EnumIMProtocol::IMProtocolWengo) { completeLogin += "@voip.wengo.fr"; } //else if (protocol == EnumIMProtocol::IMProtocolSIP) { // // TO DO ? //} } //// _imContact._contactId = completeLogin; } //// // Retrieving alias TiXmlText * alias = im.FirstChild("alias").FirstChild().Text(); if (alias) { _imContact._alias = alias->Value(); } //// //VOXOX CHANGE CJC ADD SUPPORT FOR STATUS MESSAGE // Retrieving statusMessage TiXmlText * statusMessage = im.FirstChild("statusMessage").FirstChild().Text(); if (statusMessage) { _imContact._statusMessage = statusMessage->Value(); } ///VOXOX CHANGE Marin Block option when right clicking contact 4/24/2009 TiXmlText * blocked = im.FirstChild("blocked").FirstChild().Text(); if (blocked) { String strBlocked = blocked->Value(); _imContact._blocked = strBlocked.toBoolean(); } // Retrieving icon TiXmlText * photo = im.FirstChild("photo").FirstChild().Text(); if (photo) { OWPicture picture = OWPicture::pictureFromData(Base64::decode(photo->Value())); _imContact.setIcon(picture); } //// return true; }
bool final_xml_file(const char* xml_name, cat_items_mgr& mgr) { if(xml_name == NULL)return false; TiXmlDocument* pdoc = new TiXmlDocument; TiXmlElement* root = new TiXmlElement("Items"); pdoc->LinkEndChild(root); std::map<int, cat_items>::iterator pItr = mgr.cat_items_map.begin(); for(; pItr != mgr.cat_items_map.end(); ++pItr) { cat_items* p_cat = &(pItr->second); TiXmlElement* pCat = new TiXmlElement("Cat"); pCat->SetAttribute("ID", p_cat->cat_id); pCat->SetAttribute("DbCatID", p_cat->db_cat_id); pCat->SetAttribute("Name", p_cat->name); pCat->SetAttribute("Max", p_cat->max); map<int, item_attire_data>::iterator pItr2 = p_cat->item_map.begin(); for(; pItr2 != p_cat->item_map.end(); ++pItr2) { item_attire_data* p_data= &(pItr2->second); TiXmlElement* pData = new TiXmlElement("Item"); pData->SetAttribute("ID", p_data->id); pData->SetAttribute("Name", p_data->name); pData->SetAttribute("DropLv", p_data->droplv); pData->SetAttribute("QualityLevel", p_data->quality_level); pData->SetAttribute("EquipPart", p_data->equip_part); pData->SetAttribute("Price", p_data->price); pData->SetAttribute("SellPrice", p_data->sell_price); pData->SetAttribute("RepairPrice", p_data->repair_price); pData->SetAttribute("UseLv", p_data->uselv); pData->SetAttribute("Strength", p_data->strength); pData->SetAttribute("Agility", p_data->agility); pData->SetAttribute("BodyQuality", p_data->body_quality); pData->SetAttribute("Stamina", p_data->stamina); if(strlen(p_data->atk) > 0) { pData->SetAttribute("Atk", p_data->atk); } pData->SetAttribute("Def", p_data->def); pData->SetAttribute("Duration", p_data->duration); pData->SetAttribute("Hit", p_data->hit); pData->SetAttribute("Dodge", p_data->dodge); pData->SetAttribute("Crit", p_data->crit); pData->SetAttribute("Hp", p_data->hp); pData->SetAttribute("Mp", p_data->mp); pData->SetAttribute("AddHp", p_data->add_hp); pData->SetAttribute("AddMp", p_data->add_mp); pData->SetAttribute("Slot", p_data->slot); pData->SetAttribute("Tradability", p_data->trade_ability); pData->SetAttribute("VipTradability", p_data->vip_trade_ability); pData->SetAttribute("Tradable", p_data->trade_able); pData->SetAttribute("ExploitValue", p_data->exploit_value); pData->SetAttribute("SetID", p_data->setid); pData->SetAttribute("honorLevel", p_data->honor_level); pData->SetAttribute("LifeTime", p_data->life_time); pData->SetAttribute("VipOnly", p_data->vip_only); pData->SetAttribute("DailyId", p_data->dailyid); pData->SetAttribute("decompose", p_data->decompose); pData->SetAttribute("Shop", p_data->shop); pData->SetAttribute("UnStorage", p_data->un_storage); pData->SetAttribute("resID", p_data->res_id); if(strlen(p_data->descipt) > 0) { TiXmlElement* pdescipt = new TiXmlElement("descript"); TiXmlText *pText = new TiXmlText(p_data->descipt); pText->SetCDATA(true); pdescipt->InsertEndChild(*pText); pData->InsertEndChild(*pdescipt); } pCat->InsertEndChild(*pData); } root->InsertEndChild(*pCat); } return pdoc->SaveFile(xml_name); }
bool cLanguageFile::LoadFromFile(const tString asFile) { TiXmlDocument *pDoc = hplNew(TiXmlDocument,(asFile.c_str()) ); if(pDoc->LoadFile()==false) { hplDelete(pDoc); Error("Couldn't find language file '%s'\n",asFile.c_str()); return false; } TiXmlElement *pRootElem = pDoc->FirstChildElement(); /////////////////////////// //Iterate the resources TiXmlElement *pResourceElem = pRootElem->FirstChildElement("RESOURCES"); if(pResourceElem) { TiXmlElement *pDirElem = pResourceElem->FirstChildElement("Directory"); for(; pDirElem != NULL; pDirElem = pDirElem->NextSiblingElement("Directory")) { tString sPath = pDirElem->Attribute("Path"); mpResources->AddResourceDir(sPath); } } else { Warning("No resources element found in '%s'\n",asFile.c_str()); } /////////////////////////// //Iterate the categories TiXmlElement *pCatElem = pRootElem->FirstChildElement("CATEGORY"); for(; pCatElem != NULL; pCatElem = pCatElem->NextSiblingElement("CATEGORY")) { cLanguageCategory *pCategory = hplNew( cLanguageCategory, () ); tString sCatName = pCatElem->Attribute("Name"); m_mapCategories.insert(tLanguageCategoryMap::value_type(sCatName, pCategory)); /////////////////////////// //Iterate the entries TiXmlElement *pEntryElem = pCatElem->FirstChildElement("Entry"); for(; pEntryElem != NULL; pEntryElem = pEntryElem->NextSiblingElement("Entry")) { cLanguageEntry *pEntry = hplNew( cLanguageEntry, () ); tString sEntryName = pEntryElem->Attribute("Name"); if(pEntryElem->FirstChild()==NULL) { pEntry->mwsText = _W(""); } else { TiXmlText *pTextNode = pEntryElem->FirstChild()->ToText(); if(pTextNode) { //pEntry->msText = pTextNode->Value(); //pEntry->msText = cString::ReplaceStringTo(pEntry->msText,"[br]","\n"); tString sString = pTextNode->Value(); pEntry->mwsText = _W(""); //if(sCatName == "TEST") Log("String: '%s' %d\n",sString.c_str(),sString.size()); for(size_t i=0; i< sString.length(); ++i) { unsigned char c = sString[i]; if(c=='[') { bool bFoundCommand = true; tString sCommand = ""; int lCount =1; while(sString[i+lCount] != ']' && i+lCount<sString.length() && lCount < 16) { sCommand += sString[i+lCount]; lCount++; } if(sCommand=="br") { pEntry->mwsText += _W('\n'); } else if(sCommand[0]=='u') { int lNum = cString::ToInt(sCommand.substr(1).c_str(),0); pEntry->mwsText += (wchar_t)lNum; } else { bFoundCommand = false; } //Go forward or add [ to string if(bFoundCommand) { i += lCount; } else { pEntry->mwsText += sString[i]; } } //Decode UTF-8! else if(c >= 128) { unsigned char c2 = sString[i+1]; int lNum = c & 0x1f; // c AND 0001 1111 lNum = lNum << 6; lNum = lNum | (c2 & 0x3f);// c AND 0011 1111 pEntry->mwsText += (wchar_t)lNum; ++i; //Log(" %d: (%x %x) -> %d\n",i,c,c2,(wchar_t)lNum); } else { //if(sCatName == "TEST") Log(" %d: %c | %d\n",i,c,c); pEntry->mwsText += c; //if(sCatName == "TEST") Log(" '%s'\n",cString::To8Char(pEntry->mwsText).c_str()); } } } } //if(sE == "Motion blur:") Log("After String: '%s'\n",cString::To8Char(pEntry->mwsText).c_str()); std::pair<tLanguageEntryMap::iterator,bool> ret = pCategory->m_mapEntries.insert(tLanguageEntryMap::value_type(sEntryName,pEntry)); if(ret.second==false){ Warning("Language entry '%s' in category '%s' already exists!\n",sEntryName.c_str(), sCatName.c_str()); hplDelete(pEntry); } } } hplDelete(pDoc); /*{ tString sRawFile = cString::SetFileExt(asFile,"")+"_raw_text.txt"; Log("Saving raw text '%s'\n", sRawFile.c_str()); FILE *pFile = fopen(sRawFile.c_str(),"w+"); if(pFile==NULL) Error("Could not open file: '%s'\n", sRawFile.c_str()); tLanguageCategoryMapIt CatIt = m_mapCategories.begin(); for(; CatIt != m_mapCategories.end(); ++CatIt) { cLanguageCategory *pCategory = CatIt->second; tLanguageEntryMapIt EntryIt = pCategory->m_mapEntries.begin(); for(; EntryIt != pCategory->m_mapEntries.end(); ++EntryIt) { cLanguageEntry *pEntry = EntryIt->second; fputs(cString::To8Char(pEntry->mwsText + _W("\n\n")).c_str(), pFile); } } fclose(pFile); }*/ return true; }
int CCrashDescReader::Load(CString sFileName) { TiXmlDocument doc; FILE* f = NULL; strconv_t strconv; if(m_bLoaded) return 1; // already loaded // Check that the file exists #if _MSC_VER<1400 f = _tfopen(sFileName, _T("rb")); #else _tfopen_s(&f, sFileName, _T("rb")); #endif if(f==NULL) return -1; // File can't be opened // Open XML document bool bLoaded = doc.LoadFile(f); if(!bLoaded) { fclose(f); return -2; // XML is corrupted } TiXmlHandle hDoc(&doc); TiXmlHandle hRoot = hDoc.FirstChild("CrashRpt").ToElement(); if(hRoot.ToElement()==NULL) { if(LoadXmlv10(hDoc)==0) { fclose(f); return 0; } return -3; // Invalid XML structure } // Get generator version const char* szCrashRptVersion = hRoot.ToElement()->Attribute("version"); if(szCrashRptVersion!=NULL) { m_dwGeneratorVersion = atoi(szCrashRptVersion); } // Get CrashGUID TiXmlHandle hCrashGUID = hRoot.ToElement()->FirstChild("CrashGUID"); if(hCrashGUID.ToElement()) { TiXmlText* pTextElem = hCrashGUID.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sCrashGUID = strconv.utf82t(text); } } // Get AppName TiXmlHandle hAppName = hRoot.ToElement()->FirstChild("AppName"); if(hAppName.ToElement()) { TiXmlText* pTextElem = hAppName.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sAppName = strconv.utf82t(text); } } // Get AppVersion TiXmlHandle hAppVersion = hRoot.ToElement()->FirstChild("AppVersion"); if(hAppVersion.ToElement()) { TiXmlText* pTextElem = hAppVersion.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sAppVersion = strconv.utf82t(text); } } // Get ImageName TiXmlHandle hImageName = hRoot.ToElement()->FirstChild("ImageName"); if(hImageName.ToElement()) { TiXmlText* pTextElem = hImageName.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sImageName = strconv.utf82t(text); } } // Get OperatingSystem TiXmlHandle hOperatingSystem = hRoot.ToElement()->FirstChild("OperatingSystem"); if(hOperatingSystem.ToElement()) { TiXmlText* pTextElem = hOperatingSystem.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sOperatingSystem = strconv.utf82t(text); } } // Get GeoLocation TiXmlHandle hGeoLocation = hRoot.ToElement()->FirstChild("GeoLocation"); if(hGeoLocation.ToElement()) { TiXmlText* pTextElem = hGeoLocation.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sGeoLocation = strconv.utf82t(text); } } // Get OSIs64Bit m_bOSIs64Bit = FALSE; TiXmlHandle hOSIs64Bit = hRoot.ToElement()->FirstChild("OSIs64Bit"); if(hOSIs64Bit.ToElement()) { TiXmlText* pTextElem = hOSIs64Bit.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_bOSIs64Bit = atoi(text); } } // Get SystemTimeUTC TiXmlHandle hSystemTimeUTC = hRoot.ToElement()->FirstChild("SystemTimeUTC"); if(hSystemTimeUTC.ToElement()) { TiXmlText* pTextElem = hSystemTimeUTC.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sSystemTimeUTC = strconv.utf82t(text); } } // Get ExceptionType TiXmlHandle hExceptionType = hRoot.ToElement()->FirstChild("ExceptionType"); if(hExceptionType.ToElement()) { TiXmlText* pTextElem = hExceptionType.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_dwExceptionType = atoi(text); } } // Get UserEmail TiXmlHandle hUserEmail = hRoot.ToElement()->FirstChild("UserEmail"); if(hUserEmail.ToElement()) { TiXmlText* pTextElem = hUserEmail.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sUserEmail = strconv.utf82t(text); } } // Get ProblemDecription TiXmlHandle hProblemDescription = hRoot.ToElement()->FirstChild("ProblemDescription"); if(hProblemDescription.ToElement()) { TiXmlText* pTextElem = hProblemDescription.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sProblemDescription = strconv.utf82t(text); } } // Get ExceptionCode (for SEH exceptions only) if(m_dwExceptionType==CR_SEH_EXCEPTION) { TiXmlHandle hExceptionCode = hRoot.ToElement()->FirstChild("ExceptionCode"); if(hExceptionCode.ToElement()) { TiXmlText* pTextElem = hExceptionCode.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_dwExceptionCode = atoi(text); } } } // Get FPESubcode (for FPE exceptions only) if(m_dwExceptionType==CR_CPP_SIGFPE) { TiXmlHandle hFPESubcode = hRoot.ToElement()->FirstChild("FPESubcode"); if(hFPESubcode.ToElement()) { TiXmlText* pTextElem = hFPESubcode.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_dwFPESubcode = atoi(text); } } } // Get InvParamExpression, InvParamFunction, InvParamFile, InvParamLine // (for invalid parameter exceptions only) if(m_dwExceptionType==CR_CPP_INVALID_PARAMETER) { TiXmlHandle hInvParamExpression = hRoot.ToElement()->FirstChild("InvParamExpression"); if(hInvParamExpression.ToElement()) { TiXmlText* pTextElem = hInvParamExpression.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sInvParamExpression = strconv.utf82t(text); } } TiXmlHandle hInvParamFunction = hRoot.ToElement()->FirstChild("InvParamFunction"); if(hInvParamFunction.ToElement()) { TiXmlText* pTextElem = hInvParamFunction.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sInvParamFunction = strconv.utf82t(text); } } TiXmlHandle hInvParamFile = hRoot.ToElement()->FirstChild("InvParamFile"); if(hInvParamFile.ToElement()) { TiXmlText* pTextElem = hInvParamFile.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sInvParamFile = strconv.utf82t(text); } } TiXmlHandle hInvParamLine = hRoot.ToElement()->FirstChild("InvParamLine"); if(hInvParamLine.ToElement()) { TiXmlText* pTextElem = hInvParamLine.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_dwInvParamLine = atoi(text); } } } // Get GUI resource count TiXmlHandle hGUIResourceCount = hRoot.ToElement()->FirstChild("GUIResourceCount"); if(hGUIResourceCount.ToElement()) { TiXmlText* pTextElem = hGUIResourceCount.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sGUIResourceCount = strconv.utf82t(text); } } // Get open handle count TiXmlHandle hOpenHandleCount = hRoot.ToElement()->FirstChild("OpenHandleCount"); if(hOpenHandleCount.ToElement()) { TiXmlText* pTextElem = hOpenHandleCount.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sOpenHandleCount = strconv.utf82t(text); } } // Get memory usage in KB TiXmlHandle hMemoryUsageKbytes = hRoot.ToElement()->FirstChild("MemoryUsageKbytes"); if(hMemoryUsageKbytes.ToElement()) { TiXmlText* pTextElem = hMemoryUsageKbytes.FirstChild().Text(); if(pTextElem) { const char* text = pTextElem->Value(); if(text) m_sMemoryUsageKbytes = strconv.utf82t(text); } } // Get file items list TiXmlHandle hFileList = hRoot.ToElement()->FirstChild("FileList"); if(!hFileList.ToElement()) { // This may work for reports generated by v1.2.1 hFileList = hRoot.ToElement()->FirstChild("FileItems"); } if(hFileList.ToElement()) { TiXmlHandle hFileItem = hFileList.ToElement()->FirstChild("FileItem"); while(hFileItem.ToElement()) { const char* szFileName = hFileItem.ToElement()->Attribute("name"); const char* szFileDescription = hFileItem.ToElement()->Attribute("description"); CString sFileName, sFileDescription; if(szFileName!=NULL) sFileName = strconv.utf82t(szFileName); if(szFileName!=NULL) sFileDescription = strconv.utf82t(szFileDescription); m_aFileItems[sFileName]=sFileDescription; hFileItem = hFileItem.ToElement()->NextSibling(); } } // Get custom property list TiXmlHandle hCustomProps = hRoot.ToElement()->FirstChild("CustomProps"); if(hCustomProps.ToElement()) { TiXmlHandle hProp = hCustomProps.ToElement()->FirstChild("Prop"); while(hProp.ToElement()) { const char* szName = hProp.ToElement()->Attribute("name"); const char* szValue = hProp.ToElement()->Attribute("value"); CString sName, sValue; if(szName!=NULL) sName = strconv.utf82t(szName); if(szValue!=NULL) sValue = strconv.utf82t(szValue); m_aCustomProps[sName]=sValue; hProp = hProp.ToElement()->NextSibling(); } } fclose(f); // OK m_bLoaded = true; return 0; }
void CVar::serializeCVar(TiXmlNode* rootNode, bool oldDeveloper) { if (rootNode == NULL) return; TiXmlElement* cvarNode = rootNode->FirstChildElement("CVar"); while (cvarNode != NULL) { if (!std::string(cvarNode->Attribute("name")).compare(name())) break; cvarNode = cvarNode->NextSiblingElement("CVar"); } TiXmlText* text = NULL; TiXmlText* oldText = NULL; if (!cvarNode) { cvarNode = new TiXmlElement("CVar"); cvarNode->SetAttribute("name", name()); rootNode->LinkEndChild(cvarNode); } else { if (cvarNode->FirstChild()) { oldText = cvarNode->FirstChild()->ToText(); } } switch(type()) { case CVar::Boolean: { cvarNode->SetAttribute("type", "boolean"); std::string val; if (com_developer == this) val = (oldDeveloper ? "true" : "false"); else val = (toBoolean() ? "true" : "false"); text = new TiXmlText(val); break; } case CVar::Integer: cvarNode->SetAttribute("type", "integer"); break; case CVar::Float: cvarNode->SetAttribute("type", "float"); break; case CVar::Literal: { cvarNode->SetAttribute("type", "literal"); text = new TiXmlText(toLiteral()); text->SetCDATA(true); break; } case CVar::Color: { Colori col = toColori(); cvarNode->SetAttribute("type", "color"); cvarNode->SetAttribute("r", (col.r & 255)); cvarNode->SetAttribute("g", (col.g & 255)); cvarNode->SetAttribute("b", (col.b & 255)); cvarNode->SetAttribute("a", (col.a & 255)); } break; default: break; } if (!text && type() != Color) text = new TiXmlText(toLiteral()); if (oldText && type() != Color) { cvarNode->RemoveChild(oldText); } if (text && type() != Color) cvarNode->LinkEndChild(text); }
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(), "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; }
void TLXMLLoader2::LoadFile(wxString filename, UpdateListener* updateListener) { wxString version_string = wxT("0.0"); TiXmlDocument doc(filename.mb_str()); if(!doc.LoadFile()) { wxLogError(wxT("Konnte Datei \"%s\" nicht laden"),filename.c_str()); m_data->Clear(); return; } TiXmlElement *element = doc.RootElement(); if (element==NULL) { Error(filename); return; } int snap=1; if (element->Attribute("snap",&snap)) { m_data->SetSnapValue(snap); } const char *ver; ver=element->Attribute("version"); if (ver) { /*-*/ wchar_t out[strlen(ver)]; wxEncodingConverter conv; conv.Init(wxFONTENCODING_ISO8859_2,wxFONTENCODING_UNICODE); conv.Convert(ver,out); wxString tt; tt << out; /*-*/ version_string=tt; if (version_string!=wxT("0.1") && version_string!=wxT("0.1.1") && version_string!=wxT("0.3.0") && version_string!=wxT(GG_VERSION)) { wxLogError(wxT("Couldn't load file \"%s\"\nSaved with wrong Program Version"),filename.c_str()); m_data->Clear(); return; } } TiXmlNode *node = element->FirstChild("samples"); if (node==NULL) { Error(filename); return; } int sampleNum=1; if (node->ToElement()->Attribute("count",&sampleNum)==NULL) { /**/ if (version_string!=wxT("0.0")) { Error(filename); return; } else { sampleNum=1; } } node = node->FirstChild("sample"); if (node==NULL) { //Error(filename); return; } element = node->ToElement(); for (int i=0; element; i++) { if (updateListener) if(updateListener->Update((i*100)/sampleNum)==false) return; int id; if (element->Attribute("id",&id)==NULL) { Error(filename); return; } node = element->FirstChild(); if (node==NULL) { Error(filename); return; } TiXmlText *text = node->ToText(); if (text==NULL) { Error(filename); return; } /*-*/ wchar_t out[strlen(text->Value())]; wxEncodingConverter conv; conv.Init(wxFONTENCODING_ISO8859_2,wxFONTENCODING_UNICODE); conv.Convert(text->Value(),out); wxString tt; tt << out; /*-*/ RecursiveUpdateListener s(updateListener, (i*100)/sampleNum, ((i+1)*100)/sampleNum); m_sampleManager->AddSample(tt,id,&s); /*TODO abbrechen einbauen*/ /* TODO, hier auch relative Pfadnahmen berücksichtigen*/ element=element->NextSiblingElement("sample"); } element = doc.RootElement(); if (element==NULL) { Error(filename); return; } node = element->FirstChild("tracks"); if (node==NULL) { Error(filename); return; } int trackCnt=1; if (node->ToElement()->Attribute("count",&trackCnt)==NULL) { Error(filename); return; } while(m_data->GetTrackCount()>trackCnt) { m_data->DeleteTrack(0); } while(m_data->GetTrackCount()<trackCnt) { m_data->AddTrack(-1); } node = node->FirstChild("track"); if (node==NULL) { Error(filename); return; } element = node->ToElement(); int trackNr = 0; while (element) { int id; // int pos; char buffer[100]; int mute; int volume; /*Volume und Mute einlesen*/ if (element->Attribute("mute",&mute)!=NULL) { m_data->SetTrackMute(mute,trackNr); } if (element->Attribute("volume",&volume)!=NULL) { m_data->SetTrackVolume(((double)volume)/100.0,trackNr); } node = element->FirstChild("item"); if (node!=NULL) { TiXmlElement *element_item = node->ToElement(); while (element_item) { ItemEssentials e; /* e.position = pos; e.toggleEnvelope = ; e.referenceId = 0; e.nativeEnvData = ; e.timestretch = ; e.leftTrim = ; e.rightTrim = ; e.filename = ; e.trackId = trackNr;*/ int tmp; if ( element_item->Attribute("envelope",&tmp)==NULL ) { Error(filename); return; } e.toggleEnvelope = tmp; strncpy(buffer,element_item->Attribute("leftTrim"),sizeof(buffer)); if (buffer==NULL) { //TODO: Da ist doch was im Argen Error(filename); return; } e.leftTrim = strtoll(buffer,NULL,10); strncpy(buffer,element_item->Attribute("rightTrim"),sizeof(buffer)); if (buffer==NULL) { //TODO: Da ist doch was im Argen Error(filename); return; } e.rightTrim = strtoll(buffer,NULL,10); // double tmp2; const char *p; READ_XML_FLOAT( e.nativeEnvData.leftFadeLevel, "leftFadeLevel" ) READ_XML_FLOAT( e.nativeEnvData.leftFadePos,"leftFadePos" ) READ_XML_FLOAT( e.nativeEnvData.middleLevel,"middleLevel" ) READ_XML_FLOAT( e.nativeEnvData.rightFadeLevel,"rightFadeLevel" ) READ_XML_FLOAT( e.nativeEnvData.rightFadePos,"rightFadePos" ) READ_XML_FLOAT( e.timestretch,"timestretch" ) if (e.timestretch == 0.0) { wxLogError(wxT("Timestretch must not be 0")); e.timestretch = 1.0; } /*cout << "Timestretch: " << e.timestretch << endl; cout << element_item->Attribute( "timestretch" ) << endl; cout << strtod( element_item->Attribute( "timestretch" ), 0 ) << endl; cout << strtod( "0,10001", 0 ) << endl; cout << "get_dbl: " << get_dbl( element_item->Attribute( "timestretch" ) ) << endl;*/ if (element_item->Attribute("extended",&tmp)==NULL) { e.extended = 1; } else { e.extended = tmp; } if (element_item->Attribute("sample",&id)==NULL) { Error(filename); return; } //cout << "ID: " << id << endl; strncpy(buffer,element_item->Attribute("pos"),sizeof(buffer)); if (buffer==NULL) { //TODO: Da ist doch was im Argen Error(filename); return; } gg_tl_dat pos = strtoll(buffer,NULL,10); TLSample *sample=m_sampleManager->GetSample(id); e.position = pos; e.referenceId = 0; e.trackId = trackNr; if (sample) { // m_data->AddItem(sample,pos,trackNr); m_data->AddItem( e, sample ); } element_item=element_item->NextSiblingElement("item"); } } trackNr++; element=element->NextSiblingElement("track"); }
void LevelParser::parseTileLayer (TiXmlElement *pTileElement, vector<ILayer *> *pLayers, vector<TileLayer*>* pCollisionLayers,vector<Tileset> *pTilesets){ TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, *pTilesets); //Check for layer properties bool collidable(false); for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ //cout << "Checking " << e->Value() << "\n"; if (e->Value() == string("properties")){ for (TiXmlElement* p = e->FirstChildElement(); p != NULL; p = p->NextSiblingElement()){ if (p->Value() == string("property")){ cout << "Now checking " << p->Value() << "\n"; string currentProperty = p->Attribute("name"); if (currentProperty == string("collidable")){ if (p->Attribute("value") == string("true")){ collidable = true; } else { collidable = false; } if (collidable){ cout << "Found collidable layer\n"; } } } } } } //Find data node then store it //pDataNode = findElement("data", pTileElement->FirstChildElement()); bool isBase64 = false ; bool isZlibCompressed = false; TiXmlElement* pDataNode= 0; for (TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ if (e->Value() == string("data")){ pDataNode = e; //Check if encoded/compressed if (e->Attribute("encoding")){ if (e->Attribute("encoding") == string("base64")){ isBase64 = true; } } if (e->Attribute("compression")){ if (e->Attribute("compression") == string("zlib")){ isZlibCompressed = true; } } } } //Decode data and store string decodedIDs; if (pDataNode && isBase64){ for (TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()){ TiXmlText* text = e ->ToText(); string t = text->Value(); decodedIDs = base64_decode(t); } } //Placeholder for data vector<vector<int>> data; //Calculate number of GIDS present uLongf numGids = m_width * m_height * sizeof(int); vector<unsigned> gids(numGids); //Horizontal register for vector vector<int> layerRow(m_width); //Build empty data vector to fill for(int j = 0 ; j < m_height; j++){ data.push_back(layerRow); } //Compressed data assignment if (isZlibCompressed){ uncompress ((Bytef*)&gids[0], &numGids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); for (int rows = 0 ; rows <m_height; rows++){ for (int cols = 0; cols < m_width; cols++){ data[rows][cols] = gids[rows * m_width + cols]; } } } else { //Uncompressed data assignment int index = 0; int tileID = 0; //Find all tiles, assign GID to proper data vector place for (TiXmlElement* e = pDataNode->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){ e->Attribute("gid",&tileID); data[index / m_width][index % m_width] = tileID; index++; } } //Set Tile Layer properties pTileLayer->setTileIDs(data); pTileLayer->setNumColumns(m_width); pTileLayer->setNumRows(m_height); //Save new tile layer to Level cout << "Added new layer\n"; pLayers->push_back(pTileLayer); //Add collision tiles to collision layer if (collidable){ pCollisionLayers->push_back(pTileLayer); cout << "Added new collision layer\n"; } }
// We're expecting a tag; identify what kind here and allocate the // appropriate type of node (but don't parse yet). We'll return null if // we can't find a "<" as the next non-whitespace character, or if we // find the "<" but it is followed by nothing but whitespace. Note that // we're only looking at the beginning of the tag, we won't check to see // if it is terminated properly. TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { TiXmlNode* returnNode = 0; p = SkipWhiteSpace( p, encoding ); if( !p || !*p || *p != '<' ) { return 0; // couldn't find the tag-opening "<" } TiXmlDocument* doc = GetDocument(); p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) { return 0; // a lone "<" at the end of the document } // What is this thing? // - Elements: < X where X is a letter or underscore; // white space optional between "<" and "X". // - Comments: <!-- // - Declaration: <?xml // - CDATA Text: <![CDATA[ // - All other tags are unknown to tinyxml. // const char* xmlHeader = { "<?xml" }; const char* commentHeader = { "<!--" }; const char* dtdHeader = { "<!" }; // treated as "unknown" const char* cdataHeader = { "<![CDATA[" }; if ( StringEqual( p, xmlHeader, true, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Declaration\n" ); #endif returnNode = new TiXmlDeclaration(); } else if ( StringEqual( p, commentHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Comment\n" ); #endif returnNode = new TiXmlComment(); } else if ( StringEqual( p, cdataHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing CDATA\n" ); #endif TiXmlText* text = new TiXmlText( "" ); text->SetCDATA( true ); returnNode = text; } else if ( StringEqual( p, dtdHeader, false, encoding ) ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Unknown(1)\n" ); #endif returnNode = new TiXmlUnknown(); } else if ( IsAlpha( *(p+1), encoding ) || *(p+1) == '_' ) { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Element\n" ); #endif returnNode = new TiXmlElement( "" ); } else { #ifdef DEBUG_PARSER TIXML_LOG( "XML parsing Unknown(2)\n" ); #endif returnNode = new TiXmlUnknown(); } if ( returnNode ) { // Set the parent, so it can report errors returnNode->parent = this; } else { if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } return returnNode; }
void CityManager::LoadCityConfig(const char *filename, Terrain *land) { City* TempCity; TiXmlElement* object; TiXmlElement* location; TiXmlNode* node; TiXmlDocument doc( filename ); TiXmlText* cityString; string cityName; vector<Product*> tempList; int locX, locZ; int objNum = 0; doc.LoadFile(); node = doc.FirstChild(); for(node = node->NextSibling(); node; node = node->NextSibling()) { objNum++; try { // Get the name of the city object = node->FirstChild("name")->ToElement(); if(object == NULL) throw 0; cityString = object->FirstChild()->ToText(); if(cityString == NULL) throw 0; //cityString = object->ToText(); cityName = cityString->Value(); // Get the X location location = node->FirstChild("location")->ToElement(); if(location == NULL) throw 1; object = location->FirstChild("x")->ToElement(); if(object == NULL) throw 1; cityString = object->FirstChild()->ToText(); if(cityString == NULL) throw 1; sscanf(cityString->Value(), "%d", &locX); // Get the Z location object = location->FirstChild("z")->ToElement(); if(object == NULL) throw 2; cityString = object->FirstChild()->ToText(); if(cityString == NULL) throw 2; sscanf(cityString->Value(), "%d", &locZ); TempCity = new City(land, cityName, locX, locZ); CityList.push_back(TempCity); } catch(int j) { switch (j) { case 0: Log::logger->message("Warning: Problem with Object Name."); break; case 1: Log::logger->message("Warning: Problem with Object x Location."); break; case 2: Log::logger->message("Warning: Problem with Object y Location."); break; default: Log::logger->message("Warning: Problem with City Config file."); break; } } } }
bool PostProcessingPass::load(TiXmlElement *xml) { ShaderVersion psversion = ESV_None; std::string pscode; ShaderVersion vsversion = ESV_None; std::string vscode; // Load pixel shader TiXmlNode *psnode = xml->FirstChild("pixelshader"); while (psnode) { TiXmlElement *psdata = psnode->ToElement(); if (psdata) { // Get shader code std::string code; TiXmlNode *textnode = psdata->FirstChild(); while (textnode) { TiXmlText *text = textnode->ToText(); if (text && text->Value()) { code += text->Value(); } textnode = psdata->IterateChildren(textnode); } while (isspace(code[0])) code = code.substr(1); // Get version ShaderVersion version = ESV_None; if (psdata->Attribute("type")) { if (!strcmp(psdata->Attribute("type"), "arbfp1.0") && GLEW_ARB_fragment_program) version = ESV_ARBFP10; } // Set shader to the best supported version if (version > psversion) { psversion = version; pscode = code; } } psnode = xml->IterateChildren("pixelshader", psnode); } if (psversion == ESV_None) { std::cerr << "No usable shader!" << std::endl; return false; } else if (psversion == ESV_ARBFP10) { // Build shader this->psversion = psversion; glGenProgramsARB(1, &ps); glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ps); glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, pscode.size(), pscode.c_str()); unsigned int error = glGetError(); if (error == GL_INVALID_OPERATION) { std::cout << glGetString(GL_PROGRAM_ERROR_STRING_ARB) << std::endl; std::cout << "Code: \"" << pscode << "\"" << std::endl; return false; } } else { std::cerr << "Unimplemented shader version!" << std::endl; return false; } // Load vertex shader TiXmlNode *vsnode = xml->FirstChild("vertexshader"); while (vsnode) { TiXmlElement *vsdata = vsnode->ToElement(); if (vsdata) { // Get shader code std::string code; TiXmlNode *textnode = vsdata->FirstChild(); while (textnode) { TiXmlText *text = textnode->ToText(); if (text && text->Value()) { code += text->Value(); } textnode = vsdata->IterateChildren(textnode); } while (isspace(code[0])) code = code.substr(1); // Get version ShaderVersion version = ESV_None; if (vsdata->Attribute("type")) { if (!strcmp(vsdata->Attribute("type"), "arbvp1.0") && GLEW_ARB_vertex_program) version = ESV_ARBVP10; } // Set shader to the best supported version if (version > vsversion) { vsversion = version; vscode = code; } } vsnode = xml->IterateChildren("vertexshader", vsnode); } if (vsversion == ESV_None) { std::cerr << "No usable shader!" << std::endl; return false; } else if (vsversion == ESV_ARBVP10) { // Build shader this->vsversion = vsversion; glGenProgramsARB(1, &vs); glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vs); glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, vscode.size(), vscode.c_str()); unsigned int error = glGetError(); if (error == GL_INVALID_OPERATION) { std::cout << glGetString(GL_PROGRAM_ERROR_STRING_ARB) << std::endl; std::cout << "Code: \"" << vscode << "\"" << std::endl; return false; } } else { std::cerr << "Unimplemented shader version!" << std::endl; return false; } return true; }
//Función que vuelca el contenido del fichero XML desde un nodo padre. // Se llama recursivamente hasta que se muestre todo el fichero. void cLoadXML::Output_fromNodeParent(TiXmlNode* lpParent, unsigned int luiIndent) { if ( !lpParent ) return; TiXmlNode* lpChild; TiXmlText* lpText; //Se obtiene el tipo del nodo, como un valor enumerado. Los tipos posibles son: DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT y DECLARATION. int liType = lpParent->Type(); //Se imprime la indentación (sangría). OutputDebugString(GetIndent(luiIndent, true)); int liNum; //Se actúa según el tipo de nodo. switch (liType) { //El método Value() varía según el tipo de nodo: // Document: filename of the xml file // Element: name of the element // Comment: the comment text // Unknown: the tag contents // Text: the text string case TiXmlNode::DOCUMENT: OutputDebugString("\n-------INICIO del volcado----------\n"); //Para realizar los volcados usamos "OutputDebugString". //Para concantenar lo que vamos a mostrar convertimos en string y luego se invoca a c_str() para obtener const char*. OutputDebugString(("Document: [" + (std::string)lpParent->Value() + "]").c_str()); break; case TiXmlNode::ELEMENT: OutputDebugString(("Element: [" + (std::string)lpParent->Value() + "]").c_str()); //Se invoca a la función "Output_attributes" para volcar los atributos del elemento actual, // y obtener el número de atributos. liNum=Output_attributes(lpParent->ToElement(), luiIndent+1); switch(liNum) { case 0: OutputDebugString(" (No attributes)"); break; case 1: OutputDebugString( ((std::string)GetIndent(luiIndent, false) + "1 attribute").c_str()); break; default: char lpcCadenaNum[4]; //Convertimos el número en cadena sprintf_s(lpcCadenaNum, 4, "%d", liNum); OutputDebugString( ((std::string)GetIndent(luiIndent, false) + lpcCadenaNum + " attributes").c_str()); break; } break; case TiXmlNode::COMMENT: OutputDebugString(("Comment: [" + (std::string)lpParent->Value() + "]").c_str()); break; case TiXmlNode::UNKNOWN: //Para los tipos no soportados OutputDebugString(("Unknown [" + (std::string)lpParent->Value() + "]").c_str()); break; case TiXmlNode::TEXT: lpText = lpParent->ToText(); OutputDebugString(("Text: [" + (std::string)lpText->Value() + "]").c_str()); break; case TiXmlNode::DECLARATION: OutputDebugString("Declaration"); break; default: break; } OutputDebugString("\n"); //Se llama recursivamente a esta función, empezando por el primer hijo del nodo padre y avanzando por los distintos // nodos y así iterar por todos. //En cada llamada, el nodo hijo pasa a ser el nuevo padre y se aumenta en 1 la indentación (sangría). for (lpChild = lpParent->FirstChild(); lpChild != 0; lpChild = lpChild->NextSibling()) { Output_fromNodeParent(lpChild, luiIndent+1); } if (lpChild == 0 && liType == TiXmlNode::DOCUMENT) OutputDebugString("\n-------FIN del volcado----------\n"); //Una forma alternativa de hacer la iteración por los nodos es esta: //child = 0; //while( child = parent->IterateChildren( child ) ) }
const char* TiXmlElement::ReadValue( const char* p ) { TiXmlDocument* document = GetDocument(); // Read in text and elements in any order. p = SkipWhiteSpace( p ); while ( p && *p ) { const char* start = p; while ( *p && *p != '<' ) p++; if ( !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE ); return 0; } if ( p != start ) { // Take what we have, make a text element. TiXmlText* text = new TiXmlText(); if ( !text ) { if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY ); return 0; } text->Parse( start ); if ( !text->Blank() ) LinkEndChild( text ); else delete text; } else { // We hit a '<' // Have we hit a new element or an end tag? if ( *(p+1) == '/' ) { return p; // end tag } else { // TiXmlElement* element = new TiXmlElement( "" ); // // if ( element ) // { // p = element->Parse( p+1 ); // if ( p ) // LinkEndChild( element ); // } // else // { // if ( document ) document->SetError( ERROR_OUT_OF_MEMORY ); // return 0; // } TiXmlNode* node = IdentifyAndParse( &p ); if ( node ) { LinkEndChild( node ); } else { return 0; } } } } return 0; }
void LevelParser::parseTileLayer(TiXmlElement * pTileElement, std::vector<Layer*>* pLayers, const std::vector<Tileset>* pTilesets, std::vector<TileLayer*>* pCollisionLayers) { bool collidable = false; //crar un nuevo tileLayer 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("properties")) { for (TiXmlElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement()) { if (property->Value() == std::string("property")) { if (property->Attribute("name") == std::string("coli") && property->Attribute("value") == std::string("True")) { 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); } // 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); if (collidable) { pCollisionLayers->push_back(pTileLayer); } pLayers->push_back(pTileLayer); }
OsStatus ForwardRules::parseMethodMatchContainer(const SipMessage& request, UtlString& routeToString, bool& authRequired, TiXmlNode* routeMatchNode, TiXmlNode* previousMethodMatchNode) { OsStatus fieldMatchFound = OS_FAILED; UtlString method; request.getRequestMethod(&method); TiXmlNode* methodMatchNode = previousMethodMatchNode; TiXmlElement* routeMatchElement = routeMatchNode->ToElement(); // Iterate through the children of the routeFrom container // looking for methodMatch elements while ( (methodMatchNode = routeMatchElement->IterateChildren( methodMatchNode)) && (fieldMatchFound != OS_SUCCESS) ) { // Skip non-elements if(methodMatchNode && methodMatchNode->Type() != TiXmlNode::ELEMENT) { continue; } // Skip non-methodMatch elements UtlString tagValue = methodMatchNode->Value(); if(tagValue.compareTo(XML_TAG_METHODMATCH) != 0 ) { continue; } //found methodPattern tag TiXmlElement* methodMatchElement = methodMatchNode->ToElement(); TiXmlNode* methodPatternNode = NULL; // Iteratore through the children of the methodMatch element // looking for the first methodPattern element that matches for( methodPatternNode = methodMatchElement->FirstChild( XML_TAG_METHODPATTERN); methodPatternNode; methodPatternNode = methodPatternNode->NextSibling(XML_TAG_METHODPATTERN ) ) { // Skip non-elements if(methodPatternNode && methodPatternNode->Type() != TiXmlNode::ELEMENT) { continue; } TiXmlElement* methodPatternElement = methodPatternNode->ToElement(); // Get the value contained in the methodPattern element TiXmlNode* methodPatternText = methodPatternElement->FirstChild(); if(methodPatternText && methodPatternText->Type() == TiXmlNode::TEXT) { TiXmlText* XmlMethod = methodPatternText->ToText(); if (XmlMethod) { // If the method of the request matches the method in // the methodMatch element UtlString methodString = XmlMethod->Value(); if (methodString.compareTo(method, UtlString::ignoreCase) == 0 ) { // Found a matching method, see if there is a fieldMatch // with a fieldName attribute that matches the fields // in the message fieldMatchFound = parseFieldMatchContainer(request, routeToString, authRequired, methodMatchNode); if(fieldMatchFound == OS_SUCCESS) { break; } // None of the fields matched, see if the methodMatch // element has an immediate child routeTo element. // This is the "default" if none of the fieldMatches // matched. else { fieldMatchFound = getRouteTo(routeToString, authRequired, methodMatchElement); if(fieldMatchFound == OS_SUCCESS) { break; } } } } } } } if(fieldMatchFound == OS_FAILED) { // if none of the method match were successfull or if no methodMatch node present // get the default routeTo for this routeNode. fieldMatchFound = getRouteTo(routeToString, authRequired, routeMatchNode); } return fieldMatchFound; }
/*===========================================================================*/ bool KVSMLTransferFunction::read( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); // XML document kvs::XMLDocument document; if ( !document.read( filename ) ) { kvsMessageError( "%s", document.ErrorDesc().c_str() ); BaseClass::setSuccess( false ); return false; } // <KVSML> if ( !m_kvsml_tag.read( &document ) ) { kvsMessageError( "Cannot read <%s>.", m_kvsml_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } // <TransferFunction> kvs::kvsml::TransferFunctionTag tfunc_tag; if ( !tfunc_tag.read( m_kvsml_tag.node() ) ) { kvsMessageError( "Cannot read <%s>.", tfunc_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } if ( !tfunc_tag.hasResolution() ) { kvsMessageError( "'resolution' is not specified in <%s>.", tfunc_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } m_resolution = tfunc_tag.resolution(); if ( tfunc_tag.hasMinValue() ) m_min_value = tfunc_tag.minValue(); if ( tfunc_tag.hasMaxValue() ) m_max_value = tfunc_tag.maxValue(); // <ColorMap> and <OpacityMap> kvs::kvsml::ColorMapTag color_map_tag; kvs::kvsml::OpacityMapTag opacity_map_tag; if ( color_map_tag.isExisted( tfunc_tag.node() ) ) { // Both <ColorMap> and <OpacityMap> are existed. if ( opacity_map_tag.isExisted( tfunc_tag.node() ) ) { if ( !color_map_tag.read( tfunc_tag.node() ) ) { kvsMessageError( "Cannot read <%s>.", color_map_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } // <ColorMapValue> for <ColorMap> kvs::kvsml::ColorMapValueTag color_value_tag; if ( color_value_tag.isExisted( color_map_tag.node() ) ) { kvs::XMLNode::SuperClass* node = kvs::XMLNode::FindChildNode( color_map_tag.node(), color_value_tag.name() ); while( node ) { color_value_tag.read( kvs::XMLNode::ToElement( node ) ); const float scalar = color_value_tag.scalar(); const kvs::RGBColor color = color_value_tag.color(); m_color_point_list.push_back( ColorPoint( scalar, color ) ); node = color_map_tag.node()->IterateChildren( color_value_tag.name(), node ); } } // <DataArray> for <ColorMap> else { const size_t colors_nelements = m_resolution * 3; kvs::kvsml::DataArrayTag colors; if ( !colors.read( color_map_tag.node(), colors_nelements, &m_colors ) ) { kvsMessageError( "Cannot read <%s> for <%s>.", colors.name().c_str(), color_map_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } } if ( !opacity_map_tag.read( tfunc_tag.node() ) ) { kvsMessageError( "Cannot read <%s>.", opacity_map_tag.name().c_str() ); return false; } // <OpacityMapValue> for <OpacityMap> kvs::kvsml::OpacityMapValueTag opacity_value_tag; if ( opacity_value_tag.isExisted( opacity_map_tag.node() ) ) { kvs::XMLNode::SuperClass* node = kvs::XMLNode::FindChildNode( opacity_map_tag.node(), opacity_value_tag.name() ); while( node ) { opacity_value_tag.read( kvs::XMLNode::ToElement( node ) ); const float scalar = opacity_value_tag.scalar(); const kvs::Real32 opacity = opacity_value_tag.opacity(); m_opacity_point_list.push_back( OpacityPoint( scalar, opacity ) ); node = opacity_map_tag.node()->IterateChildren( opacity_value_tag.name(), node ); } } else { // <DataArray> for <OpacityMap> const size_t opacities_nelements = m_resolution; kvs::kvsml::DataArrayTag opacities; if ( !opacities.read( opacity_map_tag.node(), opacities_nelements, &m_opacities ) ) { kvsMessageError( "Cannot read <%s> for <%s>.", opacities.name().c_str(), opacity_map_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } } } // <ColorMap> is existed, but <OpacityMap> is not existed. else { kvsMessageError( "Cannot find <%s>.", opacity_map_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } } else { // <OpacityMap> is existed, but <ColorMap> is not existed. if ( opacity_map_tag.isExisted( tfunc_tag.node() ) ) { kvsMessageError( "Cannot find <%s>.", color_map_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } else { if ( !tfunc_tag.hasFile() ) { /* <TransferFunction resolution="xxx"> * a r b g * a r b g * ....... * </TransferFunction> */ TiXmlText* values = kvs::XMLNode::ToText( tfunc_tag.node() ); if ( !values ) { kvsMessageError( "No values in <%s>", tfunc_tag.name().c_str() ); BaseClass::setSuccess( false ); return false; } const std::string delim(" \n"); kvs::Tokenizer t( values->Value(), delim ); m_opacities.allocate( m_resolution ); m_colors.allocate( m_resolution * 3 ); const size_t nloops = m_resolution; for ( size_t i = 0, i3 = 0; i < nloops; i++, i3 += 3 ) { m_opacities[ i ] = static_cast<kvs::Real32>( atof( t.token().c_str() ) ); m_colors[ i3 ] = static_cast<kvs::UInt8>( atoi( t.token().c_str() ) ); m_colors[ i3 + 1 ] = static_cast<kvs::UInt8>( atoi( t.token().c_str() ) ); m_colors[ i3 + 2 ] = static_cast<kvs::UInt8>( atoi( t.token().c_str() ) ); } } else { /* <TransferFunction resolution="xxx" file="filename.dat"/> * * "filename.dat" should be described as follows: * a r b g * a r b g * ....... */ std::ifstream ifs( tfunc_tag.file().c_str() ); if ( !ifs.is_open() ) { kvsMessageError( "Cannot open %s.", tfunc_tag.file().c_str() ); BaseClass::setSuccess( false ); return false; } m_opacities.allocate( m_resolution ); m_colors.allocate( m_resolution * 3 ); kvs::Real32 a = 0; kvs::UInt8 r = 0; kvs::UInt8 g = 0; kvs::UInt8 b = 0; for ( size_t i = 0, i3 = 0; i < m_resolution; i++, i3 += 3 ) { ifs >> a >> r >> g >> b; m_opacities[ i ] = a; m_colors[ i3 + 0 ] = r; m_colors[ i3 + 1 ] = g; m_colors[ i3 + 2 ] = b; } ifs.close(); } } } return true; }
bool CDVDStateSerializer::XMLToDVDState( dvd_state_t *state, const std::string &xmlstate ) { CXBMCTinyXML xmlDoc; xmlDoc.Parse(xmlstate.c_str()); if( xmlDoc.Error() ) return false; TiXmlHandle hRoot( xmlDoc.RootElement() ); if( strcmp( hRoot.Element()->Value(), "navstate" ) != 0 ) return false; TiXmlElement *element = NULL; TiXmlText *text = NULL; int index = 0; element = hRoot.FirstChildElement("registers").FirstChildElement("sprm").Element(); while( element ) { element->Attribute("index", &index); text = TiXmlHandle( element ).FirstChildElement("value").FirstChild().Text(); if( text && index >= 0 && index < 24 ) sscanf(text->Value(), "0x%hx", &state->registers.SPRM[index]); element = element->NextSiblingElement("sprm"); } element = hRoot.FirstChildElement("registers").FirstChildElement("gprm").Element(); while( element ) { element->Attribute("index", &index); if( index >= 0 && index < 16 ) { text = TiXmlHandle( element ).FirstChildElement("value").FirstChild().Text(); if( text ) sscanf(text->Value(), "0x%hx", &state->registers.GPRM[index]); text = TiXmlHandle( element ).FirstChildElement("mode").FirstChild().Text(); if( text ) sscanf(text->Value(), "0x%c", &state->registers.GPRM_mode[index]); text = TiXmlHandle( element ).FirstChildElement("time").FirstChildElement("tv_sec").FirstChild().Text(); if( text ) sscanf(text->Value(), "%ld", &state->registers.GPRM_time[index].tv_sec); text = TiXmlHandle( element ).FirstChildElement("time").FirstChildElement("tv_usec").FirstChild().Text(); if( text ) sscanf(text->Value(), "%ld", (long int*)&state->registers.GPRM_time[index].tv_usec); } element = element->NextSiblingElement("gprm"); } if( (text = hRoot.FirstChildElement("domain").FirstChild().Text()) ) sscanf(text->Value(), "%d", (int*) &state->domain); if( (text = hRoot.FirstChildElement("vtsn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->vtsN); if( (text = hRoot.FirstChildElement("pgcn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->pgcN); if( (text = hRoot.FirstChildElement("pgn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->pgN); if( (text = hRoot.FirstChildElement("celln").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->cellN); if( (text = hRoot.FirstChildElement("cell_restart").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->cell_restart); if( (text = hRoot.FirstChildElement("blockn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->blockN); { TiXmlHandle hrsm = hRoot.FirstChildElement("rsm"); if( (text = hrsm.FirstChildElement("vtsn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->rsm_vtsN); if( (text = hrsm.FirstChildElement("blockn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->rsm_blockN); if( (text = hrsm.FirstChildElement("pgcn").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->rsm_pgcN); if( (text = hrsm.FirstChildElement("celln").FirstChild().Text()) ) sscanf(text->Value(), "%d", &state->rsm_cellN); element = hrsm.FirstChildElement("registers").FirstChildElement("sprm").Element(); while( element ) { element->Attribute("index", &index); text = TiXmlHandle(element).FirstChildElement("value").FirstChild().Text(); if( text && index >= 0 && index < 5 ) sscanf(text->Value(), "0x%hx", &state->rsm_regs[index]); element = element->NextSiblingElement("sprm"); } } return true; }
// Parse the box from the stream CNCSError CNCSJP2File::CNCSJP2GMLGeoLocationBox::Parse(class CNCSJP2File &JP2File, CNCSJPCIOStream &Stream) { #ifdef NCS_BUILD_WITH_STDERR_DEBUG_INFO fprintf(stderr,"Parsing GML box information\n"); #endif CNCSError Error(NCS_SUCCESS); m_bValid = false; double dRegX = 0.0; double dRegY = 0.0; double p1[3]; double p2[3]; UINT32 nEPSGCode = 0; int nResults = 0; bool bSRSAttributePresent = false; UINT32 nImageWidth = JP2File.m_FileInfo.nSizeX; UINT32 nImageHeight = JP2File.m_FileInfo.nSizeY; NCSJP2_CHECKIO_BEGIN(Error, Stream); char buf[1024 + 1]; Stream.Read(buf, NCSMin((UINT32)m_nLDBox, sizeof(buf)-1)); buf[NCSMin((UINT32)m_nLDBox, sizeof(buf)-1)] = '\0'; TiXmlDocument doc; doc.Parse(buf); TiXmlHandle docHandle(&doc); TiXmlElement *GeoLocation_1 = docHandle.FirstChild("JPEG2000_GeoLocation").FirstChild("gml:RectifiedGrid").Element();//.FirstChild( "Element" ).Child( "Child", 1 ).Element(); if(GeoLocation_1 && GeoLocation_1->Attribute("gml:id") && !stricmp(GeoLocation_1->Attribute("gml:id"), "JPEG2000_GeoLocation_1")) { TiXmlElement *OriginPoint = docHandle.FirstChild("JPEG2000_GeoLocation").FirstChild("gml:RectifiedGrid").FirstChild("gml:origin").FirstChild("gml:Point").Element(); if(OriginPoint && OriginPoint->Attribute("gml:id") && !stricmp(OriginPoint->Attribute("gml:id"), "JPEG2000_Origin")) { const char *pTxt = OriginPoint->Attribute("srsName"); if(pTxt) { nResults += sscanf(pTxt, "epsg:%u", &nEPSGCode); bSRSAttributePresent = true; } TiXmlText *Coords = docHandle.FirstChild("JPEG2000_GeoLocation").FirstChild("gml:RectifiedGrid").FirstChild("gml:origin").FirstChild("gml:Point").FirstChild("gml:coordinates").FirstChild().Text(); if(Coords) { pTxt = Coords->Value(); if(pTxt) { nResults += sscanf(pTxt, "%lf,%lf", &dRegX, &dRegY); } } } TiXmlElement *offsetVector = docHandle.FirstChild("JPEG2000_GeoLocation").FirstChild("gml:RectifiedGrid").FirstChild("gml:offsetVector").Element(); if(offsetVector && offsetVector->Attribute("gml:id") && !stricmp(offsetVector->Attribute("gml:id"), "p1")) { TiXmlText *Coords = docHandle.FirstChild("JPEG2000_GeoLocation").FirstChild("gml:RectifiedGrid").FirstChild("gml:offsetVector").FirstChild().Text(); if(Coords) { const char *pTxt = Coords->Value(); if(pTxt) { nResults += sscanf(pTxt, "%lf,%lf,%lf", &p1[0], &p1[1], &p1[2]); } } offsetVector = (TiXmlElement*)offsetVector->NextSibling("gml:offsetVector"); if(offsetVector && offsetVector->Attribute("gml:id") && !stricmp(offsetVector->Attribute("gml:id"), "p2")) { TiXmlText *Coords = ((TiXmlElement*)offsetVector->FirstChild())->ToText(); if(Coords) { const char *pTxt = Coords->Value(); if(pTxt) { nResults += sscanf(pTxt, "%lf,%lf,%lf", &p2[0], &p2[1], &p2[2]); } } } } } NCSJP2_CHECKIO_END(); if((nResults == 9 && bSRSAttributePresent) || (nResults == 8 && !bSRSAttributePresent)) { IEEE8 dRegistrationX = dRegX + nImageHeight * p1[0]; IEEE8 dRegistrationY = dRegY + nImageHeight * p1[1]; if(p1[2] == 0.0 && p2[2] == 0.0) { // p1[0] = sin(Deg2Rad(dCWRotationDegrees)) * dCellSizeX; // p1[1] = cos(Deg2Rad(dCWRotationDegrees)) * dCellSizeY; // p2[0] = cos(Deg2Rad(dCWRotationDegrees)) * dCellSizeX; // p2[1] = -sin(Deg2Rad(dCWRotationDegrees)) * dCellSizeY; double dCWRotationDegrees = Rad2Deg(atan(p1[0] / p2[0])); double dCellSizeX = p2[0] / cos(atan(p1[0] / p2[0])); double dCellSizeY = p1[1] / cos(atan(p1[0] / p2[0])); m_GMLFileInfo.fOriginX = dRegistrationX; m_GMLFileInfo.fOriginY = dRegistrationY; m_GMLFileInfo.fCellIncrementX = dCellSizeX; m_GMLFileInfo.fCellIncrementY = dCellSizeY; m_GMLFileInfo.fCWRotationDegrees = dCWRotationDegrees; CNCSGDTEPSG& Epsg = *CNCSGDTEPSG::Instance(); char *pProjection = NULL; char *pDatum = NULL; NCSFree(m_GMLFileInfo.szProjection); NCSFree(m_GMLFileInfo.szDatum); if (bSRSAttributePresent && nEPSGCode && (Epsg.GetProjectionAndDatum(nEPSGCode, &pProjection, &pDatum) == NCS_SUCCESS)) { if(pProjection && pDatum) { m_GMLFileInfo.szProjection= NCSStrDup(pProjection); m_GMLFileInfo.szDatum = NCSStrDup(pDatum); NCSFree(pProjection); NCSFree(pDatum); } else if (nEPSGCode) //EPSG code present but invalid or unrecognised? { char szEPSG[32]; *szEPSG = '\0'; sprintf(szEPSG,"epsg:%u",nEPSGCode); m_GMLFileInfo.szProjection = NCSStrDup(szEPSG); m_GMLFileInfo.szDatum = NCSStrDup(szEPSG); } } else { m_GMLFileInfo.szDatum = NCSStrDup("RAW"); m_GMLFileInfo.szProjection = NCSStrDup("RAW"); } if(stricmp(m_GMLFileInfo.szProjection, "GEODETIC") == 0) m_GMLFileInfo.eCellSizeUnits = ECW_CELL_UNITS_DEGREES; else m_GMLFileInfo.eCellSizeUnits = ECW_CELL_UNITS_METERS; } else return NCS_JP2_GEODATA_READ_ERROR; } else return NCS_JP2_GEODATA_READ_ERROR; m_bValid = true; NCSStandardizeFileInfoEx(&m_GMLFileInfo); return NCS_SUCCESS; }
const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { TiXmlDocument* document = GetDocument(); // Read in text and elements in any order. const char* pWithWhiteSpace = p; p = SkipWhiteSpace( p, encoding ); while ( p && *p ) { if ( *p != '<' ) { // Take what we have, make a text element. TiXmlText* textNode = new TiXmlText( "" ); if ( !textNode ) { if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding ); return 0; } if ( TiXmlBase::IsWhiteSpaceCondensed() ) { p = textNode->Parse( p, data, encoding ); } else { // Special case: we want to keep the white space // so that leading spaces aren't removed. p = textNode->Parse( pWithWhiteSpace, data, encoding ); } if ( !textNode->Blank() ) LinkEndChild( textNode ); else delete textNode; } else { // We hit a '<' // Have we hit a new element or an end tag? This could also be // a TiXmlText in the "CDATA" style. if ( StringEqual( p, "</", false, encoding ) ) { return p; } else { TiXmlNode* node = Identify( p, encoding ); if ( node ) { p = node->Parse( p, data, encoding ); LinkEndChild( node ); } else { return 0; } } } pWithWhiteSpace = p; p = SkipWhiteSpace( p, encoding ); } if ( !p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding ); } return p; }
std::string Kml::PointPlacemark( TiXmlElement* document, RoutePoint* routepoint ) { TiXmlElement* pmPoint = new TiXmlElement( "Placemark" ); document->LinkEndChild( pmPoint ); TiXmlElement* pmPointName = new TiXmlElement( "name" ); pmPoint->LinkEndChild( pmPointName ); TiXmlText* pmPointNameVal = new TiXmlText( routepoint->GetName().mb_str( wxConvUTF8 ) ); pmPointName->LinkEndChild( pmPointNameVal ); TiXmlElement* pointDescr = new TiXmlElement( "description" ); pmPoint->LinkEndChild( pointDescr ); bool descrIsPlainText = true; wxCharBuffer descrString = routepoint->m_MarkDescription.mb_str( wxConvUTF8 ); if( insertQtVlmExtendedData ) { // Does the RoutePoint description parse as XML with an <ExtendedData> root tag? TiXmlDocument descrDoc; TiXmlElement* extendedData; if( descrDoc.Parse( descrString, 0, TIXML_ENCODING_UTF8 ) ) { if( 0 == strncmp( descrDoc.RootElement()->Value(), "ExtendedData", 12 ) ) { descrIsPlainText = false; extendedData = descrDoc.RootElement(); TiXmlHandle docHandle( &descrDoc ); TiXmlElement* seq = docHandle.FirstChild( "ExtendedData" ).FirstChild( "vlm:sequence" ).ToElement(); if( ! seq ) { seq = new TiXmlElement( "vlm:sequence" ); TiXmlText* snVal = new TiXmlText( wxString::Format( _T("%04d"), seqCounter ).mb_str( wxConvUTF8 ) ); seq->LinkEndChild( snVal ); descrDoc.RootElement()->LinkEndChild( seq ); } pmPoint->LinkEndChild( descrDoc.RootElement()->Clone() ); } } if( descrIsPlainText ) { // We want Sequence names but there was some non-parsing stuff in the description. // Push that into a sub-tag of an XML formatted description. extendedData = new TiXmlElement( "ExtendedData" ); pmPoint->LinkEndChild( extendedData ); TiXmlElement* seq = new TiXmlElement( "vlm:sequence" ); extendedData->LinkEndChild( seq ); TiXmlText* snVal = new TiXmlText( wxString::Format( _T("%04d"), seqCounter ).mb_str( wxConvUTF8 ) ); seq->LinkEndChild( snVal ); if( routepoint->m_MarkDescription.Length() ) { TiXmlElement* data = new TiXmlElement( "Data" ); data->SetAttribute( "name", "Description" ); extendedData->LinkEndChild( data ); TiXmlElement* value = new TiXmlElement( "value" ); data->LinkEndChild( value ); TiXmlText* txtVal = new TiXmlText( descrString ); value->LinkEndChild( txtVal ); } } if( extendedData && seqCounter == 0 ) { const wxCharBuffer ownshipPos = wxString::Format( _T("%f %f"), gLon, gLat ).mb_str( wxConvUTF8 ); TiXmlHandle h( extendedData ); TiXmlElement* route = h.FirstChild( "vlm:route" ).ToElement(); TiXmlElement* ownship = h.FirstChild( "vlm:route" ).FirstChild( "ownship" ).ToElement(); if( route ) { if( ownship ) { TiXmlText* owns = ownship->FirstChild()->ToText(); if( owns ) { owns->SetValue( ownshipPos ); } else { owns = new TiXmlText( ownshipPos ); ownship->LinkEndChild( owns ); } } else { ownship = new TiXmlElement( "ownship" ); route->LinkEndChild( ownship ); TiXmlText* owns = new TiXmlText( ownshipPos ); ownship->LinkEndChild( owns ); } } else { route = new TiXmlElement( "vlm:route" ); extendedData->LinkEndChild( route ); ownship = new TiXmlElement( "ownship" ); route->LinkEndChild( ownship ); TiXmlText* owns = new TiXmlText( ownshipPos ); ownship->LinkEndChild( owns ); } } } else { // Add description as dumb text. TiXmlText* pointDescrVal = new TiXmlText( descrString ); pointDescr->LinkEndChild( pointDescrVal ); } TiXmlElement* point = new TiXmlElement( "Point" ); pmPoint->LinkEndChild( point ); TiXmlElement* pointCoord = new TiXmlElement( "coordinates" ); point->LinkEndChild( pointCoord ); std::stringstream pointCoordStr; pointCoordStr << routepoint->m_lon << "," << routepoint->m_lat << ",0. "; TiXmlText* pointText = new TiXmlText( pointCoordStr.str() ); pointCoord->LinkEndChild( pointText ); return pointCoordStr.str(); }