void DividendTuningOptFileRoutines::generateTuningNodes(const std::vector<LWSKernelPar> macroVecs) { XMLNode * tnode = doc.NewElement( "DIVIDEND" ); XMLNode * lnode = doc.NewElement( "LWGS" ); doc.InsertFirstChild(tnode); tnode->InsertFirstChild(lnode); for (unsigned i=0; i<macroVecs.size(); i++) { std::stringstream kernelStr; kernelStr << KERNEL_STR << "_" << KernelToken++; XMLElement *kElement = doc.NewElement( "Kernel" ); XMLNode * kNode = tnode->InsertFirstChild( kElement ); std::stringstream cstr; cstr << " Tuning parameters for " << kernelStr.str(); kElement->SetAttribute("identifier", macroVecs[i].getIdentifier().c_str()); kElement->SetAttribute("kernelid", macroVecs[i].getKernelId()); kElement->SetAttribute("dim", macroVecs[i].getDim()); XMLNode *cNode = kNode->InsertFirstChild(doc.NewComment(cstr.str().c_str())); //Dump dimention information XMLNode *pNode = cNode; const vector<LWSMacro> lwsM = macroVecs[i].getLWSMacros(); for (unsigned j=0; j< lwsM.size(); j++) { XMLElement *dElement = doc.NewElement("Dim"); dElement->SetAttribute("index", j); dElement->SetAttribute("macro", lwsM[j].getMacroName().c_str()); dElement->SetAttribute("start", lwsM[j].getStart()); dElement->SetAttribute("end", lwsM[j].getEnd()); dElement->SetAttribute("step", lwsM[j].getStep()); dElement->SetAttribute("default", lwsM[j].getDefault()); XMLNode *tmp = kNode->InsertAfterChild(pNode, dElement); pNode = tmp; } lnode->InsertEndChild( kElement ); } tnode->InsertEndChild(lnode); doc.InsertEndChild(tnode); }
void example_5() { printf( "XML Example 5\n" ); // Test: Programmatic DOM // Build: // <element> // <!--comment--> // <sub attrib="1" /> // <sub attrib="2" /> // <sub attrib="3" >& Text!</sub> // <element> XMLDocument* doc = new XMLDocument(); XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) ); XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) }; for( int i=0; i<3; ++i ) { sub[i]->SetAttribute( "attrib", i ); } element->InsertEndChild( sub[2] ); XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) ); element->InsertAfterChild( comment, sub[0] ); element->InsertAfterChild( sub[0], sub[1] ); sub[2]->InsertFirstChild( doc->NewText( "& Text!" )); doc->Print(); doc->SaveFile( "pretty.xml" ); doc->SaveFile( "compact.xml", true ); delete doc; }
/** * Write the current object */ void MetadataTranslator::OnWrite( const Object * pObject, pcstr pszName, Context & ctxt, XMLNode & elem ) { const Metadata* pmetadata = dynamic_cast< const Metadata*>(pObject); if( pmetadata == NULL) throw TranslationException("MetadataTranslator cannot cast Metadata object"); XMLElement* pelemc = elem.GetDocument()->NewElement( pszName); //Set the namespace for the Metadata. pelemc->SetAttribute( "xmlns", METADATA_NAMESPACE); //Fill out id, artifacts, and comments last in accordance //with schema. WriteAttributedObject( *pmetadata, ctxt, *pelemc); WriteList<AnyUri>( pmetadata->Includes(), "include", ctxt, *pelemc); WriteList<Band>( pmetadata->Bands(), "band", ctxt, *pelemc); WriteList<IonStream>( pmetadata->Streams(), "stream", ctxt, *pelemc); WriteList<Lump>( pmetadata->Lumps(), "lump", ctxt, *pelemc); WriteList<Chunk>( pmetadata->Chunks(), "chunks", ctxt, *pelemc); WriteList<Block>( pmetadata->Blocks(), "blocks", ctxt, *pelemc); WriteList<Lane>( pmetadata->Lanes(), "lane", ctxt, *pelemc); WriteList<System>( pmetadata->Systems(), "system", ctxt, *pelemc); WriteList<Session>( pmetadata->Sessions(), "session", ctxt, *pelemc); WriteList<File>( pmetadata->Files(), "file", ctxt, *pelemc); WriteList<FileSet>( pmetadata->FileSets(), "fileset", ctxt, *pelemc); elem.InsertEndChild( pelemc); }
void emu::Settings::CreateDefaultXml(char const * filename) { cpumode = "interpeter-slow"; gerenderer = "pspe4all-hal.video.OGL4"; XMLDocument xmlDoc; XMLNode * pRoot = xmlDoc.NewElement("pspe4all"); xmlDoc.InsertFirstChild(pRoot); XMLElement * pElement = xmlDoc.NewElement("GeneralSettings"); XMLElement * pListElement = xmlDoc.NewElement("CpuMode"); pListElement->SetText(cpumode.c_str()); pElement->InsertEndChild(pListElement); XMLElement * pListElement2 = xmlDoc.NewElement("GeRenderer"); pListElement2->SetText(gerenderer.c_str()); pElement->InsertEndChild(pListElement2); pRoot->InsertEndChild(pElement); xmlDoc.SaveFile(filename); }
bool CGBFile<GeomType, ValueType>::save(const std::string& directoryname, const std::string& fn, const Volume3d<GeomType, ValueType>& volume) { const std::string& filename = directoryname + "/" + fn; XMLDocument xml; XMLDeclaration* decl = xml.NewDeclaration(); xml.InsertEndChild(decl); XMLNode* root = xml.NewElement("root"); xml.InsertEndChild(root); { XMLElement* res = xml.NewElement(resStr.c_str()); res->SetAttribute("x", volume.getResolutions()[0]); res->SetAttribute("y", volume.getResolutions()[1]); res->SetAttribute("z", volume.getResolutions()[2]); root->InsertEndChild(res); } root->InsertEndChild( create(xml, originStr, volume.getStart()) ); root->InsertEndChild( create(xml, "length", volume.getSpace().getLengths())); imageFileNames.clear(); { XMLElement* e = xml.NewElement("volume"); e->SetAttribute("type", "unsigned char"); e->SetAttribute("format", "png"); VolumeFile vFile(directoryname); for (size_t i = 0; i < volume.getResolutions()[2]; ++i) { const auto iFile = vFile.toImageFile( "image", i, ImageFile::Type::PNG); XMLElement* elem = xml.NewElement("image"); const auto& str = iFile.getFileNameIncludingPath(); elem->SetAttribute("path", str.c_str()); e->InsertEndChild(elem); imageFileNames.push_back(str); } root->InsertEndChild(e); } //for (size_t i = 0; i < ) xml.SaveFile(filename.c_str()); return true; }
static void DumpProfilingInfo() { XMLDocument doc; XMLDeclaration *d = doc.NewDeclaration(); DIVIDEND_EXIT_ERROR_ON(d== NULL, -1, "Invalid XML Declaratio"); doc.InsertEndChild(d); XMLNode * tnode = doc.NewElement( "DIVIDEND" ); XMLNode * lnode = doc.NewElement( "LWGS" ); DIVIDEND_EXIT_ERROR_ON(tnode == NULL, -1, "Failed to crate a node"); DIVIDEND_EXIT_ERROR_ON(lnode == NULL, -1, "Failed to crate a node"); doc.InsertFirstChild(tnode); tnode->InsertFirstChild(lnode); for (unsigned i=0; i<profEventIndex; i++) { XMLElement *kElement = doc.NewElement( "Kernel" ); XMLNode * kNode = tnode->InsertFirstChild( kElement ); kElement->SetAttribute("id",KPI[i].kernel_id); float time = 0.0; for (unsigned j=0; j<KPI[i].idx; j++) { //clGetEventProfilingInfo(KPI[i].event[j], CL_PROFILING_COMMAND_START, sizeof(KPI[i].time_starti[j]), &(KPI[i].time_start[j]), NULL); //clGetEventProfilingInfo(KPI[i].event[j], CL_PROFILING_COMMAND_END, sizeof(KPI[i].time_end[j]), &(KPI[i].time_end[j]), NULL); time = time + (KPI[i].time_end[j] - KPI[i].time_start[j])/1000000.0; } time = time / (float) KPI[i].idx; kElement->SetAttribute("time", time); lnode->InsertEndChild( kElement ); } tnode->InsertEndChild(lnode); doc.InsertEndChild(tnode); doc.SaveFile(DIVIDEND_PROF_FILE_NAME); }
void OutputWriter::WriteInitOutput(ResponseMsg response){ std::string path = CommandManager::getPathOut(); tinyxml2::XMLDocument* doc = CommandManager::getDocOut(); doc->Clear(); //Clear all text XMLNode *root = doc->NewElement("init"); XMLText* textCode = doc->NewText((Utils::convertInt(response.getCode()).c_str())); XMLText* textMessage = doc->NewText(response.getMessage()); XMLElement* codeElement = doc->NewElement("code"); root->InsertEndChild(codeElement); XMLElement* messageElement = doc->NewElement("message"); root->InsertEndChild(messageElement); codeElement->InsertEndChild(textCode); messageElement->InsertEndChild(textMessage); doc->InsertEndChild(root); doc->SaveFile(path.c_str()); }
void OutputWriter::WriteCommandNotFormat(){ std::string path = CommandManager::getPathOut(); tinyxml2::XMLDocument* doc = CommandManager::getDocOut(); XMLNode *root = doc->NewElement("command"); XMLText* textCode = doc->NewText((Utils::convertInt(CAMERROR_VALUE_UNKNOWN)).c_str()); XMLElement* codeElement = doc->NewElement("code"); root->InsertEndChild(codeElement); codeElement->InsertEndChild(textCode); XMLElement* commandsElement = doc->FirstChildElement("commands"); commandsElement->InsertEndChild(root); }
void emu::Settings::Save(char const * filename) { XMLDocument xmlDoc; XMLNode * pRoot = xmlDoc.NewElement("pspe4all"); xmlDoc.InsertFirstChild(pRoot); XMLElement * pElement = xmlDoc.NewElement("GeneralSettings"); XMLElement * pListElement = xmlDoc.NewElement("CpuMode"); pListElement->SetText(cpumode.c_str()); pElement->InsertEndChild(pListElement); XMLElement * pListElement2 = xmlDoc.NewElement("GeRenderer"); pListElement2->SetText(gerenderer.c_str()); pElement->InsertEndChild(pListElement2); pRoot->InsertEndChild(pElement); xmlDoc.SaveFile(filename); }
int main( int argc, const char ** argv ) { #if defined( _MSC_VER ) && defined( DEBUG ) _CrtMemCheckpoint( &startMemState ); #endif #if defined(_MSC_VER) || defined(MINGW32) || defined(__MINGW32__) #if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR //MINGW64: both 32 and 64-bit mkdir( "resources/out/" ); #else _mkdir( "resources/out/" ); #endif #else mkdir( "resources/out/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif if ( argc > 1 ) { XMLDocument* doc = new XMLDocument(); clock_t startTime = clock(); doc->LoadFile( argv[1] ); clock_t loadTime = clock(); int errorID = doc->ErrorID(); delete doc; doc = 0; clock_t deleteTime = clock(); printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID ); if ( !errorID ) { printf( "Load time=%u\n", (unsigned)(loadTime - startTime) ); printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) ); printf( "Total time=%u\n", (unsigned)(deleteTime - startTime) ); } exit(0); } FILE* fp = fopen( "resources/dream.xml", "r" ); if ( !fp ) { printf( "Error opening test file 'dream.xml'.\n" "Is your working directory the same as where \n" "the xmltest.cpp and dream.xml file are?\n\n" #if defined( _MSC_VER ) "In windows Visual Studio you may need to set\n" "Properties->Debugging->Working Directory to '..'\n" #endif ); exit( 1 ); } fclose( fp ); XMLTest( "Example-1", 0, example_1() ); XMLTest( "Example-2", 0, example_2() ); XMLTest( "Example-3", 0, example_3() ); XMLTest( "Example-4", true, example_4() ); /* ------ Example 2: Lookup information. ---- */ { static const char* test[] = { "<element />", "<element></element>", "<element><subelement/></element>", "<element><subelement></subelement></element>", "<element><subelement><subsub/></subelement></element>", "<!--comment beside elements--><element><subelement></subelement></element>", "<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>", "<element attrib1='foo' attrib2=\"bar\" ></element>", "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>", "<element>Text inside element.</element>", "<element><b></b></element>", "<element>Text inside and <b>bolded</b> in the element.</element>", "<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>", "<element>This & That.</element>", "<element attrib='This<That' />", 0 }; for( int i=0; test[i]; ++i ) { XMLDocument doc; doc.Parse( test[i] ); doc.Print(); printf( "----------------------------------------------\n" ); } } #if 1 { static const char* test = "<!--hello world\n" " line 2\r" " line 3\r\n" " line 4\n\r" " line 5\r-->"; XMLDocument doc; doc.Parse( test ); doc.Print(); } { static const char* test = "<element>Text before.</element>"; XMLDocument doc; doc.Parse( test ); XMLElement* root = doc.FirstChildElement(); XMLElement* newElement = doc.NewElement( "Subelement" ); root->InsertEndChild( newElement ); doc.Print(); } { XMLDocument* doc = new XMLDocument(); static const char* test = "<element><sub/></element>"; doc->Parse( test ); delete doc; } { // Test: Programmatic DOM // Build: // <element> // <!--comment--> // <sub attrib="1" /> // <sub attrib="2" /> // <sub attrib="3" >& Text!</sub> // <element> XMLDocument* doc = new XMLDocument(); XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) ); XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) }; for( int i=0; i<3; ++i ) { sub[i]->SetAttribute( "attrib", i ); } element->InsertEndChild( sub[2] ); XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) ); element->InsertAfterChild( comment, sub[0] ); element->InsertAfterChild( sub[0], sub[1] ); sub[2]->InsertFirstChild( doc->NewText( "& Text!" )); doc->Print(); XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() ); XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) ); XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) ); XMLTest( "Programmatic DOM", "& Text!", doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() ); // And now deletion: element->DeleteChild( sub[2] ); doc->DeleteNode( comment ); element->FirstChildElement()->SetAttribute( "attrib", true ); element->LastChildElement()->DeleteAttribute( "attrib" ); XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) ); int value = 10; int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value ); XMLTest( "Programmatic DOM", result, (int)XML_NO_ATTRIBUTE ); XMLTest( "Programmatic DOM", value, 10 ); doc->Print(); { XMLPrinter streamer; doc->Print( &streamer ); printf( "%s", streamer.CStr() ); } { XMLPrinter streamer( 0, true ); doc->Print( &streamer ); XMLTest( "Compact mode", "<element><sub attrib=\"1\"/><sub/></element>", streamer.CStr(), false ); } doc->SaveFile( "./resources/out/pretty.xml" ); doc->SaveFile( "./resources/out/compact.xml", true ); delete doc; } { // Test: Dream // XML1 : 1,187,569 bytes in 31,209 allocations // XML2 : 469,073 bytes in 323 allocations //int newStart = gNew; XMLDocument doc; doc.LoadFile( "resources/dream.xml" ); doc.SaveFile( "resources/out/dreamout.xml" ); doc.PrintError(); XMLTest( "Dream", "xml version=\"1.0\"", doc.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false ); XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLDocument doc2; doc2.LoadFile( "resources/out/dreamout.xml" ); XMLTest( "Dream-out", "xml version=\"1.0\"", doc2.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false ); XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc2.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream-out", "And Robin shall restore amends.", doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); //gNewTotal = gNew - newStart; } { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; XMLDocument doc; doc.Parse( error ); XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE ); } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; XMLDocument doc; doc.Parse( str ); XMLElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XMLTest( "Query attribute: int as double", result, (int)XML_NO_ERROR ); XMLTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XMLTest( "Query attribute: double as double", result, (int)XML_NO_ERROR ); XMLTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XMLTest( "Query attribute: double as int", result, (int)XML_NO_ERROR ); XMLTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XMLTest( "Query attribute: not a number", result, (int)XML_WRONG_ATTRIBUTE_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XMLTest( "Query attribute: does not exist", result, (int)XML_NO_ATTRIBUTE ); } { const char* str = "<doc/>"; XMLDocument doc; doc.Parse( str ); XMLElement* ele = doc.FirstChildElement(); int iVal, iVal2; double dVal, dVal2; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); ele->QueryAttribute( "int", &iVal2 ); ele->QueryAttribute( "double", &dVal2 ); XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" ); XMLTest( "Attribute round trip. c-string.", "strValue", cStr ); XMLTest( "Attribute round trip. int.", 1, iVal ); XMLTest( "Attribute round trip. double.", -1, (int)dVal ); XMLTest( "Alternate query", true, iVal == iVal2 ); XMLTest( "Alternate query", true, dVal == dVal2 ); } { XMLDocument doc; doc.LoadFile( "resources/utf8test.xml" ); // Get the attribute "value" from the "Russian" element and check it. XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" ); 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" ) ); 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>"; XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText(); XMLTest( "UTF-8: Browsing russian element name.", russianText, text->Value() ); // Now try for a round trip. doc.SaveFile( "resources/out/utf8testout.xml" ); // Check the round trip. int okay = 0; FILE* saved = fopen( "resources/out/utf8testout.xml", "r" ); FILE* verify = fopen( "resources/utf8testverify.xml", "r" ); if ( saved && verify ) { okay = 1; char verifyBuf[256]; while ( fgets( verifyBuf, 256, verify ) ) { char savedBuf[256]; fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); okay = 0; break; } } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay ); } // --------GetText()----------- { const char* str = "<foo>This is text</foo>"; XMLDocument doc; doc.Parse( str ); const XMLElement* element = doc.RootElement(); XMLTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Parse( str ); element = doc.RootElement(); XMLTest( "GetText() contained element.", element->GetText() == 0, true ); } // ---------- CDATA --------------- { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); doc.Print(); XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", false ); } // ----------- CDATA ------------- { const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); doc.Print(); XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", false ); } // InsertAfterChild causes crash. { // InsertBeforeChild and InsertAfterChild causes crash. XMLDocument doc; XMLElement* parent = doc.NewElement( "Parent" ); doc.InsertFirstChild( parent ); XMLElement* childText0 = doc.NewElement( "childText0" ); XMLElement* childText1 = doc.NewElement( "childText1" ); XMLNode* childNode0 = parent->InsertEndChild( childText0 ); XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 ); XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true ); } { // 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>"; XMLDocument doc; doc.Parse( passages ); XMLElement* 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( "resources/out/textfile.txt", "w" ); if ( textfile ) { XMLPrinter streamer( textfile ); psg->Accept( &streamer ); fclose( textfile ); } textfile = fopen( "resources/out/textfile.txt", "r" ); TIXMLASSERT( 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.\"/>\n", buf, false ); fclose( textfile ); } } { // Suppress entities. const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'.\">Crazy &ttk;</psg>" "</passages>"; XMLDocument doc( false ); doc.Parse( passages ); XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ), "Line 5 has "quotation marks" and 'apostrophe marks'." ); XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(), "Crazy &ttk;" ); doc.Print(); } { const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>"; XMLDocument doc; doc.Parse( test ); XMLTest( "dot in names", doc.Error(), false ); XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" ); XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" ); } { const char* test = "<element><Name>1.1 Start easy ignore fin thickness
</Name></element>"; XMLDocument doc; doc.Parse( test ); XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XMLTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n", false ); } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; XMLDocument doc; doc.Parse( doctype ); doc.SaveFile( "resources/out/test7.xml" ); doc.DeleteChild( doc.RootElement() ); doc.LoadFile( "resources/out/test7.xml" ); doc.Print(); const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown(); XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() ); } { // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; XMLDocument doc; doc.Parse( doctype ); XMLComment* comment = doc.FirstChild()->ToComment(); XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues) doc.PrintError(); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Embedded null throws error.", true, doc.Error() ); } { // Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; XMLDocument doc; doc.Parse( str ); XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() ); } { // Low entities XMLDocument doc; doc.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result ); doc.Print(); } { // Attribute values with trailing quotes not handled correctly XMLDocument doc; doc.Parse( "<foo attribute=bar\" />" ); XMLTest( "Throw error with bad end quotes.", doc.Error(), true ); } { // [ 1663758 ] Failure to report error on bad XML XMLDocument xml; xml.Parse("<x>"); XMLTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XMLTest("Missing end tag with trailing whitespace", xml.Error(), true); xml.Parse("<x></y>"); XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT); } { // [ 1475201 ] TinyXML parses entities in comments XMLDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); XMLNode* e0 = xml.FirstChild(); XMLNode* e1 = e0->NextSibling(); XMLComment* c0 = e0->ToComment(); XMLComment* c1 = e1->ToComment(); XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XMLTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } { XMLDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); xml.Print(); int count = 0; for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild(); ele; ele = ele->NextSibling() ) { ++count; } XMLTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; XMLDocument doc; doc.Parse( (const char*)buf); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. XMLDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XMLTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop XMLDocument xml; xml.Parse( "<infinite>loop" ); XMLTest( "Infinite loop test.", true, true ); } #endif { const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>"; XMLDocument doc; doc.Parse( pub ); XMLDocument clone; for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) { XMLNode* copy = node->ShallowClone( &clone ); clone.InsertEndChild( copy ); } clone.Print(); int count=0; const XMLNode* a=clone.FirstChild(); const XMLNode* b=doc.FirstChild(); for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) { ++count; XMLTest( "Clone and Equal", true, a->ShallowEqual( b )); } XMLTest( "Clone and Equal", 4, count ); } { // This shouldn't crash. XMLDocument doc; if(XML_NO_ERROR != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" )) { doc.PrintError(); } XMLTest( "Error in snprinf handling.", true, doc.Error() ); } { // Attribute ordering. static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />"; XMLDocument doc; doc.Parse( xml ); XMLElement* ele = doc.FirstChildElement(); const XMLAttribute* a = ele->FirstAttribute(); XMLTest( "Attribute order", "1", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "2", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "3", a->Value() ); XMLTest( "Attribute order", "attrib3", a->Name() ); ele->DeleteAttribute( "attrib2" ); a = ele->FirstAttribute(); XMLTest( "Attribute order", "1", a->Value() ); a = a->Next(); XMLTest( "Attribute order", "3", a->Value() ); ele->DeleteAttribute( "attrib1" ); ele->DeleteAttribute( "attrib3" ); XMLTest( "Attribute order (empty)", false, ele->FirstAttribute() ? true : false ); } { // Make sure an attribute with a space in it succeeds. static const char* xml0 = "<element attribute1= \"Test Attribute\"/>"; static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>"; static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>"; XMLDocument doc0; doc0.Parse( xml0 ); XMLDocument doc1; doc1.Parse( xml1 ); XMLDocument doc2; doc2.Parse( xml2 ); XMLElement* ele = 0; ele = doc0.FirstChildElement(); XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) ); ele = doc1.FirstChildElement(); XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) ); ele = doc2.FirstChildElement(); XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) ); } { // Make sure we don't go into an infinite loop. static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>"; XMLDocument doc; doc.Parse( xml ); XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement(); XMLElement* ele1 = ele0->NextSiblingElement(); bool equal = ele0->ShallowEqual( ele1 ); XMLTest( "Infinite loop in shallow equal.", true, equal ); } // -------- Handles ------------ { static const char* xml = "<element attrib='bar'><sub>Text</sub></element>"; XMLDocument doc; doc.Parse( xml ); XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement(); XMLTest( "Handle, success, mutable", ele->Value(), "sub" ); XMLHandle docH( doc ); ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement(); XMLTest( "Handle, dne, mutable", false, ele != 0 ); } { static const char* xml = "<element attrib='bar'><sub>Text</sub></element>"; XMLDocument doc; doc.Parse( xml ); XMLConstHandle docH( doc ); const XMLElement* ele = docH.FirstChildElement( "element" ).FirstChild().ToElement(); XMLTest( "Handle, success, const", ele->Value(), "sub" ); ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement(); XMLTest( "Handle, dne, const", false, ele != 0 ); } { // Default Declaration & BOM XMLDocument doc; doc.InsertEndChild( doc.NewDeclaration() ); doc.SetBOM( true ); XMLPrinter printer; doc.Print( &printer ); static const char* result = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; XMLTest( "BOM and default declaration", printer.CStr(), result, false ); XMLTest( "CStrSize", printer.CStrSize(), 42, false ); } { const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Ill formed XML", true, doc.Error() ); } // QueryXYZText { const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>"; XMLDocument doc; doc.Parse( xml ); const XMLElement* pointElement = doc.RootElement(); int intValue = 0; unsigned unsignedValue = 0; float floatValue = 0; double doubleValue = 0; bool boolValue = false; pointElement->FirstChildElement( "y" )->QueryIntText( &intValue ); pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue ); pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue ); pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue ); pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue ); XMLTest( "QueryIntText", intValue, 1, false ); XMLTest( "QueryUnsignedText", unsignedValue, (unsigned)1, false ); XMLTest( "QueryFloatText", floatValue, 1.2f, false ); XMLTest( "QueryDoubleText", doubleValue, 1.2, false ); XMLTest( "QueryBoolText", boolValue, true, false ); } { const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>"; XMLDocument doc; doc.Parse( xml ); XMLTest( "Non-alpha element lead letter parses.", doc.Error(), false ); } { const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>"; XMLDocument doc; doc.Parse( xml ); XMLTest("Non-alpha attribute lead character parses.", doc.Error(), false); } { const char* xml = "<3lement></3lement>"; XMLDocument doc; doc.Parse( xml ); XMLTest("Element names with lead digit fail to parse.", doc.Error(), true); } { const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE"; XMLDocument doc; doc.Parse( xml, 10 ); XMLTest( "Set length of incoming data", doc.Error(), false ); } { XMLDocument doc; doc.LoadFile( "resources/dream.xml" ); doc.Clear(); XMLTest( "Document Clear()'s", doc.NoChildren(), true ); } // ----------- Whitespace ------------ { const char* xml = "<element>" "<a> This \nis ' text ' </a>" "<b> This is ' text ' \n</b>" "<c>This is ' \n\n text '</c>" "</element>"; XMLDocument doc( true, COLLAPSE_WHITESPACE ); doc.Parse( xml ); const XMLElement* element = doc.FirstChildElement(); for( const XMLElement* parent = element->FirstChildElement(); parent; parent = parent->NextSiblingElement() ) { XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() ); } } #if 0 { // Passes if assert doesn't fire. XMLDocument xmlDoc; xmlDoc.NewDeclaration(); xmlDoc.NewComment("Configuration file"); XMLElement *root = xmlDoc.NewElement("settings"); root->SetAttribute("version", 2); } #endif { const char* xml = "<element> </element>"; XMLDocument doc( true, COLLAPSE_WHITESPACE ); doc.Parse( xml ); XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() ); } #if 0 // the question being explored is what kind of print to use: // https://github.com/leethomason/tinyxml2/issues/63 { const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9'/>"; XMLDocument doc; doc.Parse( xml ); doc.FirstChildElement()->SetAttribute( "attrA", 123456789.123456789 ); doc.FirstChildElement()->SetAttribute( "attrB", 1.001e9 ); doc.Print(); } #endif { // An assert should not fire. const char* xml = "<element/>"; XMLDocument doc; doc.Parse( xml ); XMLElement* ele = doc.NewElement( "unused" ); // This will get cleaned up with the 'doc' going out of scope. XMLTest( "Tracking unused elements", true, ele != 0, false ); } { const char* xml = "<parent><child>abc</child></parent>"; XMLDocument doc; doc.Parse( xml ); XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child"); XMLPrinter printer; ele->Accept( &printer ); XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false ); } { XMLDocument doc; XMLError error = doc.LoadFile( "resources/empty.xml" ); XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error ); } { // BOM preservation static const char* xml_bom_preservation = "\xef\xbb\xbf<element/>\n"; { XMLDocument doc; XMLTest( "BOM preservation (parse)", XML_NO_ERROR, doc.Parse( xml_bom_preservation ), false ); XMLPrinter printer; doc.Print( &printer ); XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true ); doc.SaveFile( "resources/bomtest.xml" ); } { XMLDocument doc; doc.LoadFile( "resources/bomtest.xml" ); XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false ); XMLPrinter printer; doc.Print( &printer ); XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true ); } } { // Insertion with Removal const char* xml = "<?xml version=\"1.0\" ?>" "<root>" "<one>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</one>" "<two/>" "</root>"; const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<two>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</two>" "</root>"; const char* xmlAfterOne = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "<two/>" "</root>"; const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>" "<root>" "<one/>" "<two/>" "<subtree>" "<elem>element 1</elem>text<!-- comment -->" "</subtree>" "</root>"; XMLDocument doc; doc.Parse( xml ); XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); XMLElement* two = doc.RootElement()->FirstChildElement("two"); two->InsertFirstChild(subtree); XMLPrinter printer1( 0, true ); doc.Accept( &printer1 ); XMLTest( "Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr()); doc.Parse( xml ); subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); two = doc.RootElement()->FirstChildElement("two"); doc.RootElement()->InsertAfterChild(two, subtree); XMLPrinter printer2( 0, true ); doc.Accept( &printer2 ); XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false ); doc.Parse( xml ); XMLNode* one = doc.RootElement()->FirstChildElement("one"); subtree = one->FirstChildElement("subtree"); doc.RootElement()->InsertAfterChild(one, subtree); XMLPrinter printer3( 0, true ); doc.Accept( &printer3 ); XMLTest( "Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false ); doc.Parse( xml ); subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree"); two = doc.RootElement()->FirstChildElement("two"); doc.RootElement()->InsertEndChild(subtree); XMLPrinter printer4( 0, true ); doc.Accept( &printer4 ); XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false ); } // ----------- Performance tracking -------------- { #if defined( _MSC_VER ) __int64 start, end, freq; QueryPerformanceFrequency( (LARGE_INTEGER*) &freq ); #endif FILE* fp = fopen( "resources/dream.xml", "r" ); fseek( fp, 0, SEEK_END ); long size = ftell( fp ); fseek( fp, 0, SEEK_SET ); char* mem = new char[size+1]; fread( mem, size, 1, fp ); fclose( fp ); mem[size] = 0; #if defined( _MSC_VER ) QueryPerformanceCounter( (LARGE_INTEGER*) &start ); #else clock_t cstart = clock(); #endif static const int COUNT = 10; for( int i=0; i<COUNT; ++i ) { XMLDocument doc; doc.Parse( mem ); } #if defined( _MSC_VER ) QueryPerformanceCounter( (LARGE_INTEGER*) &end ); #else clock_t cend = clock(); #endif delete [] mem; static const char* note = #ifdef DEBUG "DEBUG"; #else "Release"; #endif #if defined( _MSC_VER ) printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) ); #else printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT ); #endif } #if defined( _MSC_VER ) && defined( DEBUG ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); //printf( "new total=%d\n", gNewTotal ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
int main( int /*argc*/, const char ** /*argv*/ ) { #if defined( _MSC_VER ) && defined( DEBUG ) _CrtMemCheckpoint( &startMemState ); #endif #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated. #endif FILE* fp = fopen( "dream.xml", "r" ); if ( !fp ) { printf( "Error opening test file 'dream.xml'.\n" "Is your working directory the same as where \n" "the xmltest.cpp and dream.xml file are?\n\n" #if defined( _MSC_VER ) "In windows Visual Studio you may need to set\n" "Properties->Debugging->Working Directory to '..'\n" #endif ); exit( 1 ); } fclose( fp ); #if defined(_MSC_VER) #pragma warning ( pop ) #endif /* ------ Example 1: Load and parse an XML file. ---- */ { XMLDocument doc; doc.LoadFile( "dream.xml" ); } /* ------ Example 2: Lookup information. ---- */ { XMLDocument doc; doc.LoadFile( "dream.xml" ); // Structure of the XML file: // - Element "PLAY" the root Element // - - Element "TITLE" child of the root PLAY Element // - - - Text child of the TITLE Element // Navigate to the title, using the convenience function, with a dangerous lack of error checking. const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText(); printf( "Name of play (1): %s\n", title ); // Text is just another Node to TinyXML-2. The more general way to get to the XMLText: XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText(); title = textNode->Value(); printf( "Name of play (2): %s\n", title ); } { static const char* test[] = { "<element />", "<element></element>", "<element><subelement/></element>", "<element><subelement></subelement></element>", "<element><subelement><subsub/></subelement></element>", "<!--comment beside elements--><element><subelement></subelement></element>", "<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>", "<element attrib1='foo' attrib2=\"bar\" ></element>", "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>", "<element>Text inside element.</element>", "<element><b></b></element>", "<element>Text inside and <b>bolded</b> in the element.</element>", "<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>", "<element>This & That.</element>", "<element attrib='This<That' />", 0 }; for( int i=0; test[i]; ++i ) { XMLDocument doc; doc.Parse( test[i] ); doc.Print(); printf( "----------------------------------------------\n" ); } } #if 1 { static const char* test = "<!--hello world\n" " line 2\r" " line 3\r\n" " line 4\n\r" " line 5\r-->"; XMLDocument doc; doc.Parse( test ); doc.Print(); } { static const char* test = "<element>Text before.</element>"; XMLDocument doc; doc.Parse( test ); XMLElement* root = doc.FirstChildElement(); XMLElement* newElement = doc.NewElement( "Subelement" ); root->InsertEndChild( newElement ); doc.Print(); } { XMLDocument* doc = new XMLDocument(); static const char* test = "<element><sub/></element>"; doc->Parse( test ); delete doc; } { // Test: Programmatic DOM // Build: // <element> // <!--comment--> // <sub attrib="1" /> // <sub attrib="2" /> // <sub attrib="3" >& Text!</sub> // <element> XMLDocument* doc = new XMLDocument(); XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) ); XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) }; for( int i=0; i<3; ++i ) { sub[i]->SetAttribute( "attrib", i ); } element->InsertEndChild( sub[2] ); XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) ); element->InsertAfterChild( comment, sub[0] ); element->InsertAfterChild( sub[0], sub[1] ); sub[2]->InsertFirstChild( doc->NewText( "& Text!" )); doc->Print(); XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() ); XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) ); XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) ); XMLTest( "Programmatic DOM", "& Text!", doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() ); // And now deletion: element->DeleteChild( sub[2] ); doc->DeleteNode( comment ); element->FirstChildElement()->SetAttribute( "attrib", true ); element->LastChildElement()->DeleteAttribute( "attrib" ); XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) ); int value = 10; int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value ); XMLTest( "Programmatic DOM", result, XML_NO_ATTRIBUTE ); XMLTest( "Programmatic DOM", value, 10 ); doc->Print(); XMLPrinter streamer; doc->Print( &streamer ); printf( "%s", streamer.CStr() ); delete doc; } { // Test: Dream // XML1 : 1,187,569 bytes in 31,209 allocations // XML2 : 469,073 bytes in 323 allocations //int newStart = gNew; XMLDocument doc; doc.LoadFile( "dream.xml" ); doc.SaveFile( "dreamout.xml" ); doc.PrintError(); XMLTest( "Dream", "xml version=\"1.0\"", doc.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false ); XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLTest( "Dream", "And Robin shall restore amends.", doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); XMLDocument doc2; doc2.LoadFile( "dreamout.xml" ); XMLTest( "Dream-out", "xml version=\"1.0\"", doc2.FirstChild()->ToDeclaration()->Value() ); XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false ); XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"", doc2.FirstChild()->NextSibling()->ToUnknown()->Value() ); XMLTest( "Dream-out", "And Robin shall restore amends.", doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() ); //gNewTotal = gNew - newStart; } { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; XMLDocument doc; doc.Parse( error ); XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE ); } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; XMLDocument doc; doc.Parse( str ); XMLElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XMLTest( "Query attribute: int as double", result, XML_NO_ERROR ); 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, XML_NO_ERROR ); XMLTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XMLTest( "Query attribute: not a number", result, XML_WRONG_ATTRIBUTE_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XMLTest( "Query attribute: does not exist", result, XML_NO_ATTRIBUTE ); } { const char* str = "<doc/>"; XMLDocument doc; doc.Parse( str ); XMLElement* ele = doc.FirstChildElement(); int iVal; double dVal; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" ); XMLTest( "Attribute round trip. c-string.", "strValue", cStr ); XMLTest( "Attribute round trip. int.", 1, iVal ); XMLTest( "Attribute round trip. double.", -1, (int)dVal ); } { XMLDocument doc; doc.LoadFile( "utf8test.xml" ); // Get the attribute "value" from the "Russian" element and check it. XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" ); 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" ) ); 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>"; XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText(); XMLTest( "UTF-8: Browsing russian element name.", russianText, text->Value() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 0; #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated. #endif FILE* saved = fopen( "utf8testout.xml", "r" ); FILE* verify = fopen( "utf8testverify.xml", "r" ); #if defined(_MSC_VER) #pragma warning ( pop ) #endif if ( saved && verify ) { okay = 1; while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); okay = 0; break; } } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay ); } // --------GetText()----------- { const char* str = "<foo>This is text</foo>"; XMLDocument doc; doc.Parse( str ); const XMLElement* element = doc.RootElement(); XMLTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Parse( str ); element = doc.RootElement(); XMLTest( "GetText() contained element.", element->GetText() == 0, true ); } // ---------- CDATA --------------- { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); doc.Print(); XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", false ); } // ----------- CDATA ------------- { const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; XMLDocument doc; doc.Parse( str ); doc.Print(); XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", false ); } // InsertAfterChild causes crash. { // InsertBeforeChild and InsertAfterChild causes crash. XMLDocument doc; XMLElement* parent = doc.NewElement( "Parent" ); doc.InsertFirstChild( parent ); XMLElement* childText0 = doc.NewElement( "childText0" ); XMLElement* childText1 = doc.NewElement( "childText1" ); XMLNode* childNode0 = parent->InsertEndChild( childText0 ); XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 ); XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true ); } { // 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>"; XMLDocument doc; doc.Parse( passages ); XMLElement* 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 ); #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated. #endif FILE* textfile = fopen( "textfile.txt", "w" ); #if defined(_MSC_VER) #pragma warning ( pop ) #endif if ( textfile ) { XMLPrinter streamer( textfile ); psg->Accept( &streamer ); fclose( textfile ); } #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated. #endif textfile = fopen( "textfile.txt", "r" ); #if defined(_MSC_VER) #pragma warning ( pop ) #endif TIXMLASSERT( 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.\"/>\n", buf, false ); } fclose( textfile ); } { // Suppress entities. const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'.\">Crazy &ttk;</psg>" "</passages>"; XMLDocument doc( false ); doc.Parse( passages ); XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ), "Line 5 has "quotation marks" and 'apostrophe marks'." ); XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(), "Crazy &ttk;" ); doc.Print(); } { const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>"; XMLDocument doc; doc.Parse( test ); XMLTest( "dot in names", doc.Error(), 0); XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" ); XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" ); } { const char* test = "<element><Name>1.1 Start easy ignore fin thickness
</Name></element>"; XMLDocument doc; doc.Parse( test ); XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XMLTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n", false ); } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; XMLDocument doc; doc.Parse( doctype ); doc.SaveFile( "test7.xml" ); doc.DeleteChild( doc.RootElement() ); doc.LoadFile( "test7.xml" ); doc.Print(); const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown(); XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() ); } { // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; XMLDocument doc; doc.Parse( doctype ); XMLComment* comment = doc.FirstChild()->ToComment(); XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues) doc.PrintError(); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; XMLDocument doc; doc.Parse( doctype ); XMLTest( "Embedded null throws error.", true, doc.Error() ); } { // Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; XMLDocument doc; doc.Parse( str ); XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() ); } { // Low entities XMLDocument doc; doc.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result ); doc.Print(); } { // Attribute values with trailing quotes not handled correctly XMLDocument doc; doc.Parse( "<foo attribute=bar\" />" ); XMLTest( "Throw error with bad end quotes.", doc.Error(), true ); } { // [ 1663758 ] Failure to report error on bad XML XMLDocument xml; xml.Parse("<x>"); XMLTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XMLTest("Missing end tag with trailing whitespace", xml.Error(), true); xml.Parse("<x></y>"); XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT); } { // [ 1475201 ] TinyXML parses entities in comments XMLDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); XMLNode* e0 = xml.FirstChild(); XMLNode* e1 = e0->NextSibling(); XMLComment* c0 = e0->ToComment(); XMLComment* c1 = e1->ToComment(); XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XMLTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } { XMLDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); xml.Print(); int count = 0; for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild(); ele; ele = ele->NextSibling() ) { ++count; } XMLTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; XMLDocument doc; doc.Parse( (const char*)buf); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. XMLDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XMLTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop XMLDocument xml; xml.Parse( "<infinite>loop" ); XMLTest( "Infinite loop test.", true, true ); } #endif { const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>"; XMLDocument doc; doc.Parse( pub ); XMLDocument clone; for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) { XMLNode* copy = node->ShallowClone( &clone ); clone.InsertEndChild( copy ); } clone.Print(); int count=0; const XMLNode* a=clone.FirstChild(); const XMLNode* b=doc.FirstChild(); for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) { ++count; XMLTest( "Clone and Equal", true, a->ShallowEqual( b )); } XMLTest( "Clone and Equal", 4, count ); } // ----------- Performance tracking -------------- { #if defined( _MSC_VER ) __int64 start, end, freq; QueryPerformanceFrequency( (LARGE_INTEGER*) &freq ); #endif #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated. #endif FILE* fp = fopen( "dream.xml", "r" ); #if defined(_MSC_VER) #pragma warning ( pop ) #endif fseek( fp, 0, SEEK_END ); long size = ftell( fp ); fseek( fp, 0, SEEK_SET ); char* mem = new char[size+1]; fread( mem, size, 1, fp ); fclose( fp ); mem[size] = 0; #if defined( _MSC_VER ) QueryPerformanceCounter( (LARGE_INTEGER*) &start ); #else clock_t cstart = clock(); #endif static const int COUNT = 10; for( int i=0; i<COUNT; ++i ) { XMLDocument doc; doc.Parse( mem ); } #if defined( _MSC_VER ) QueryPerformanceCounter( (LARGE_INTEGER*) &end ); #else clock_t cend = clock(); #endif delete [] mem; static const char* note = #ifdef DEBUG "DEBUG"; #else "Release"; #endif #if defined( _MSC_VER ) printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) ); #else printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT ); #endif } #if defined( _MSC_VER ) && defined( DEBUG ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); //printf( "new total=%d\n", gNewTotal ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return 0; }
int Effect::saveEffect(char* filepath) { XMLDocument doc; XMLNode* effect = doc.NewElement("Effect"); doc.InsertFirstChild(effect); for (auto emitter : emitterVec) { /****Constructor stuff****/ XMLNode* emitterNode = doc.NewElement("Emitter"); effect->InsertEndChild(emitterNode); XMLElement* element = doc.NewElement("OutputType"); element->SetText(emitter->getOutputType()); emitterNode->InsertEndChild(element); element = doc.NewElement("Position"); glm::vec3 position = emitter->getLocalPosition(); element->SetAttribute("x", position.x); element->SetAttribute("y", position.y); element->SetAttribute("z", position.z); emitterNode->InsertEndChild(element); element = doc.NewElement("EmitterLifetime"); element->SetText(emitter->getEmitterLifetime()); emitterNode->InsertEndChild(element); element = doc.NewElement("EmitFrequency"); element->SetText(emitter->getEmitFrequency()); emitterNode->InsertEndChild(element); element = doc.NewElement("ParticlesPerEmit"); element->SetText(emitter->getParticlesPerEmit()); emitterNode->InsertEndChild(element); element = doc.NewElement("ParticleLiftime"); element->SetText(emitter->getParticleLifetime()); emitterNode->InsertEndChild(element); element = doc.NewElement("ParticleMortal"); element->SetText(emitter->getParticleMortality()); emitterNode->InsertEndChild(element); /****other necessary stuff****/ //Geometry Shader element = doc.NewElement("UseGeometryShader"); element->SetText(emitter->getUseGeometryShader()); emitterNode->InsertEndChild(element); //Movable element = doc.NewElement("Movable"); element->SetText(emitter->getMovable()); emitterNode->InsertEndChild(element); //Start time element = doc.NewElement("StartTime"); element->SetText(emitter->getStartTime()); emitterNode->InsertEndChild(element); //Velocity element = doc.NewElement("Velocity"); element->SetText(emitter->getVelocityType()); emitterNode->InsertEndChild(element); //Physic element = doc.NewElement("Physic"); if (emitter->getPhysicTrajectory()){ XMLElement* physic = doc.NewElement("Trajectory"); XMLElement* gravity = doc.NewElement("Gravity"); glm::vec4 gravityVec = emitter->getGravity(); gravity->SetAttribute("x", gravityVec.x); gravity->SetAttribute("y", gravityVec.y); gravity->SetAttribute("z", gravityVec.z); gravity->SetAttribute("w", gravityVec.w); physic->InsertEndChild(gravity); XMLElement* speed = doc.NewElement("Speed"); speed->SetText(emitter->getSpeed()); physic->InsertEndChild(speed); element->InsertEndChild(physic); } else if (emitter->getPhysicDirectionGravity()){ XMLElement* physic = doc.NewElement("DirectionGravity"); XMLElement* temp = doc.NewElement("Gravity"); glm::vec4 gravityVec = emitter->getGravity(); temp->SetAttribute("x", gravityVec.x); temp->SetAttribute("y", gravityVec.y); temp->SetAttribute("z", gravityVec.z); temp->SetAttribute("w", gravityVec.w); physic->InsertEndChild(temp); temp = doc.NewElement("Speed"); temp->SetText(emitter->getSpeed()); physic->InsertEndChild(temp); element->InsertEndChild(physic); } else if (emitter->getPhysicPointGravity()){ XMLElement* physic = doc.NewElement("PointGravity"); XMLElement* temp = doc.NewElement("Point"); glm::vec4 gravityVec = emitter->getGravity(); temp->SetAttribute("x", gravityVec.x); temp->SetAttribute("y", gravityVec.y); temp->SetAttribute("z", gravityVec.z); physic->InsertEndChild(temp); //TODO impact + backtosource temp = doc.NewElement("GravityImpact"); temp->SetText(emitter->getPhysicAttGravityImpact()); physic->InsertEndChild(temp); temp = doc.NewElement("Speed"); temp->SetText(emitter->getSpeed()); physic->InsertEndChild(temp); temp = doc.NewElement("GravityRange"); temp->SetText(emitter->getPhysicAttGravityRange()); physic->InsertEndChild(temp); temp = doc.NewElement("GravityFunction"); temp->SetText(emitter->getPhysicAttGravityFunction()); physic->InsertEndChild(temp); element->InsertEndChild(physic); temp = doc.NewElement("BackToSource"); temp->SetText(emitter->getPhysicAttUseLocalCoordinates()); physic->InsertEndChild(temp); } else if (emitter->getPhysicSwarmCircleMotion()){ XMLElement* physic = doc.NewElement("SwarmCircleMotion"); XMLElement* temp = doc.NewElement("MovementVertical"); temp->SetText(emitter->getPhysicAttMovementVertical()); physic->InsertEndChild(temp); temp = doc.NewElement("MovementHorizontalX"); temp->SetText(emitter->getPhysicAttMovementHorizontalX()); physic->InsertEndChild(temp); temp = doc.NewElement("MovementHorizontalZ"); temp->SetText(emitter->getPhysicAttMovementHorizontalZ()); physic->InsertEndChild(temp); temp = doc.NewElement("Speed"); temp->SetText(emitter->getSpeed()); physic->InsertEndChild(temp); element->InsertEndChild(physic); } emitterNode->InsertEndChild(element); //Area emitting element = doc.NewElement("AreaEmitter"); bool on = emitter->getAreaEmittingXY() | emitter->getAreaEmittingXZ(); element->SetAttribute("on", on); if (on){ XMLElement* temp = doc.NewElement("AreaXY"); temp->SetText(emitter->getAreaEmittingXY()); element->InsertEndChild(temp); temp = doc.NewElement("AreaXZ"); temp->SetText(emitter->getAreaEmittingXZ()); element->InsertEndChild(temp); temp = doc.NewElement("Size"); temp->SetText(emitter->getAreaSize()); element->InsertEndChild(temp); temp = doc.NewElement("Accuracy"); temp->SetText(emitter->getAreaAccuracy()); element->InsertEndChild(temp); } emitterNode->InsertEndChild(element); //Textures element = doc.NewElement("Texture"); int k = 0; for (auto texture : emitter->m_textureList) { XMLElement* tex = doc.NewElement("Tex"); tex->SetText(texture->getFilepath()); tex->SetAttribute("time", emitter->blendingTime[k]); element->InsertEndChild(tex); k++; } if (emitter->getTexUseScaling()) { XMLElement* scaling = doc.NewElement("Scaling"); XMLElement* tex = doc.NewElement("UseTexture"); tex->SetText(emitter->getUseTexture()); scaling->InsertEndChild(tex); tex = doc.NewElement("ScalingSize"); for (int i = 1; i < emitter->getTexScalingCount(); i = i + 2){ XMLElement* item = doc.NewElement("Item"); item->SetText(emitter->m_scalingData[i]); tex->InsertEndChild(item); } scaling->InsertEndChild(tex); tex = doc.NewElement("ScalingMoment"); for (int i = 0; i < emitter->getTexScalingCount(); i = i + 2){ XMLElement* item = doc.NewElement("Item"); item->SetText(emitter->m_scalingData[i]); tex->InsertEndChild(item); } scaling->InsertEndChild(tex); tex = doc.NewElement("BirthTime"); tex->SetText(emitter->getTexBirthTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("DeathTime"); tex->SetText(emitter->getTexDeathTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("BlendingTime"); tex->SetText(emitter->getTexBlendingTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("RotateLeft"); tex->SetText(emitter->getTexRotateLeft()); scaling->InsertEndChild(tex); tex = doc.NewElement("RotationSpeed"); tex->SetText(emitter->getRotationSpeed()); scaling->InsertEndChild(tex); element->InsertEndChild(scaling); } else { XMLElement* scaling = doc.NewElement("Size"); XMLElement* tex = doc.NewElement("UseTexture"); tex->SetText(emitter->getUseTexture()); scaling->InsertEndChild(tex); tex = doc.NewElement("ParticleSize"); tex->SetText(emitter->getTexParticleDefaultSize()); scaling->InsertEndChild(tex); tex = doc.NewElement("BirthTime"); tex->SetText(emitter->getTexBirthTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("DeathTime"); tex->SetText(emitter->getTexDeathTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("BlendingTime"); tex->SetText(emitter->getTexBlendingTime()); scaling->InsertEndChild(tex); tex = doc.NewElement("RotateLeft"); tex->SetText(emitter->getTexRotateLeft()); scaling->InsertEndChild(tex); tex = doc.NewElement("RotationSpeed"); tex->SetText(emitter->getRotationSpeed()); scaling->InsertEndChild(tex); element->InsertEndChild(scaling); } emitterNode->InsertEndChild(element); } //save the file XMLError error = doc.SaveFile(filepath); XMLCheckResult(error); printf("EFFECT: saving Effect successfully\n"); return XML_SUCCESS; }
bool DividendTuningOptFileRoutines::dumpSearchResult(const std::vector<DividendLWSKernelConf> confs, string& fname) { fname = DIVIDEND_LWS_TUNING_RESULT_PREFIX; time_t rawtime; struct tm *info; char buffer[80]; time( &rawtime ); info = localtime( &rawtime ); strftime(buffer,80,"-%Y%m%dT%H%M%S%z", info); fname = fname + buffer; fname = fname + ".xml"; XMLDocument doc; doc.InsertEndChild (doc.NewDeclaration() ); XMLNode *tnode = doc.NewElement( "DIVIDEND" ); XMLNode *lnode = doc.NewElement( "LWGS" ); XMLNode *kkNode = NULL; for (unsigned i=0; i<confs.size(); i++) { const DividendLWSKernelConf& c = confs[i]; XMLElement * knode = doc.NewElement( "kernel" ); knode->SetAttribute("id", c.kernel_id); knode->SetAttribute("dim", c.best.dim); knode->SetAttribute("rsize", (unsigned int)c.confs.size()); XMLNode *pcNode = NULL; for (unsigned j=0; j<c.confs.size(); j++) { const DividendLWSConf& CC = c.confs[j]; XMLElement * ccnode = doc.NewElement( "config" ); ccnode->SetAttribute("id", j); ccnode->SetAttribute("runtime", (double)CC.time); ccnode->SetAttribute("speedup", CC.defaultT / CC.time); ccnode->SetAttribute("ci", CC.ci); if (pcNode) { knode->InsertAfterChild(pcNode, ccnode); } else { knode->InsertFirstChild(ccnode); } pcNode = ccnode; XMLElement *ppNode = NULL; for (unsigned k=0; k<CC.dim; k++) { XMLElement *mnode = doc.NewElement ("paramter"); mnode->SetAttribute("macroname", CC.macroName[k].c_str()); mnode->SetAttribute("val", CC.val[k]); if (ppNode) { ccnode->InsertAfterChild(ppNode, mnode); } else { ccnode->InsertFirstChild(mnode); } ppNode = mnode; } } if (kkNode) { lnode->InsertAfterChild(kkNode, knode); } else { lnode->InsertFirstChild(knode); } kkNode = knode; } tnode->InsertEndChild(lnode); doc.InsertEndChild(tnode); return doc.SaveFile(fname.c_str()) == XML_NO_ERROR; }
int testWriteDoc(string fileName) { //https://shilohjames.wordpress.com/2014/04/27/tinyxml2-tutorial/#XML-CreateXMLDocument tinyxml2::XMLDocument temp; XMLNode * root = temp.NewElement("Root"); temp.InsertFirstChild(root); XMLElement * element = temp.NewElement("tuixml"); element->SetAttribute("background", "black"); { XMLElement * rectangle = temp.NewElement("rectangle"); rectangle->SetAttribute("text", ""); rectangle->SetAttribute("x", 0); rectangle->SetAttribute("y", 0); rectangle->SetAttribute("width", "30"); rectangle->SetAttribute("height", "35"); rectangle->SetAttribute("foreground", "yellow"); rectangle->SetAttribute("background", "red"); XMLElement * text = temp.NewElement("text"); rectangle->InsertEndChild(text); element->InsertEndChild(rectangle); } for(int counter = 0, y = 0; counter < 6; counter++, y+=6) { srand (time(NULL)); for(int counter1 = 0, x = 31; counter1 < 9; x+=6, counter1++ ) { string colours[] = {"black", "red", "green", "blue", "magenta", "cyan", "white"}; int background = rand() % 6 + 1; int foreground = rand() % 6 + 1; char yString[5] = {'\0'}; char xString[5] = {'\0'}; sprintf(yString,"%d", y); sprintf(xString,"%d", x); XMLElement * rectangle = temp.NewElement("rectangle"); rectangle->SetAttribute("text", ""); rectangle->SetAttribute("x", xString); rectangle->SetAttribute("y", yString); rectangle->SetAttribute("width", "5"); rectangle->SetAttribute("height", "5"); rectangle->SetAttribute("foreground", colours[foreground].c_str()); rectangle->SetAttribute("background", colours[background].c_str()); XMLElement * text = temp.NewElement("text"); rectangle->InsertEndChild(text); element->InsertEndChild(rectangle); } } for(int counter = 0, y = 0; counter < 6; counter++, y+=6) { srand (time(NULL)); for(int counter1 = 0, x = 85; counter1 < 9; x+=6, counter1++ ) { string colours[] = {"black", "red", "green", "blue", "magenta", "cyan", "white"}; int background = rand() % 5 + 1; int foreground = rand() % 5 + 1; char yString[5] = {'\0'}; char xString[5] = {'\0'}; sprintf(yString,"%d", y); sprintf(xString,"%d", x); XMLElement * rectangle = temp.NewElement("rectangle"); rectangle->SetAttribute("text", ""); rectangle->SetAttribute("x", xString); rectangle->SetAttribute("y", yString); rectangle->SetAttribute("width", "5"); rectangle->SetAttribute("height", "5"); rectangle->SetAttribute("foreground", colours[foreground].c_str()); rectangle->SetAttribute("background", colours[background].c_str()); XMLElement * text = temp.NewElement("text"); rectangle->InsertEndChild(text); element->InsertEndChild(rectangle); } } for(int counter = 0, y = 0; counter < 6; counter++, y+=6) { char textString[10][100] = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth"}; char yString[5] = {'\0'}; sprintf(yString,"%d", y); XMLElement * text = temp.NewElement("text"); text->SetAttribute("text", textString[counter]); text->SetAttribute("x", "100"); text->SetAttribute("y", yString); text->SetAttribute("width", "10"); text->SetAttribute("height", "5"); text->SetAttribute("foreground", "blue"); text->SetAttribute("background", "white"); element->InsertEndChild(text); } root->InsertEndChild(element); return temp.SaveFile(fileName.c_str()); }
bool LevelParser::writeLevel(const Level &level, std::string name) { XMLDocument tmxFile; // Insert root element and its attributes XMLNode *pRoot = tmxFile.NewElement("map"); tmxFile.InsertFirstChild(pRoot); XMLElement * pElement = tmxFile.RootElement(); // Another option here would be taking the biggest width, height and tilewidth from level's tilelayers // width pElement->SetAttribute("width", level.getWidth()); // height pElement->SetAttribute("height", level.getHeight()); // tilewidth pElement->SetAttribute("tilewidth", level.getTileSize()); // tileheight pElement->SetAttribute("tileheight", level.getTileSize()); // musicID pElement->SetAttribute("musicID", level.getMusic().c_str()); // write level layers int tileLayers = 1, objLayers = 1, bckLayers = 1; for (auto pLayer : level.m_layers) { std::string layerID = pLayer->getLayerID(); if (layerID == "OBJECT")// && (dynamic_cast<ObjectLayer*>(pLayer)->getGameObjects()->size() != 0)) { pElement = tmxFile.NewElement("objectgroup"); writeObjectLayer(pElement, dynamic_cast<ObjectLayer*>(pLayer), "Object Layer " + to_string(objLayers)); objLayers++; // Insert object layer node pRoot->InsertEndChild(pElement); } else if (layerID == "TILE") { pElement = tmxFile.NewElement("layer"); writeTileLayer(pElement, dynamic_cast<TileLayer*>(pLayer), "Tile Layer " + to_string(tileLayers)); tileLayers++; // Insert tile layer node pRoot->InsertEndChild(pElement); } else if (layerID == "BACKGROUND") { pElement = tmxFile.NewElement("background"); writeObjectLayer(pElement, dynamic_cast<BckLayer*>(pLayer), "Background Layer " + to_string(bckLayers)); bckLayers++; pRoot->InsertEndChild(pElement); } } if (tmxFile.SaveFile(name.c_str()) == XML_NO_ERROR) { return true; } else { std::cout << "An error has ocurred writing file " << name << ". TinyXML error: " << tmxFile.ErrorName() << std::endl; return false; } }
bool saveOutputXML(OutputXML *xml, string path) { cout << "Salvando..." << endl; XMLDocument doc; // root node XMLNode * testInput = doc.NewElement("testinput"); // cabe�alho XMLElement * dataset = doc.NewElement("dataset"); dataset->SetAttribute("id", xml->id.c_str()); testInput->InsertFirstChild(dataset); // tempos XMLElement * times = doc.NewElement("execution_time"); for (auto _t : xml->all_times) { // ignora esse elemento if (_t.first == Task::ALL) continue; // calcula a media e desvio padrao double m, d; Helper::mediaDesvioDouble(_t.second, m, d); // adiciona no xml XMLElement * time = doc.NewElement("time"); time->SetAttribute("name", Task::getName(_t.first).c_str()); time->SetAttribute("mean", m); time->SetAttribute("stddev", d); times->InsertEndChild(time); } testInput->InsertEndChild(times); // frames XMLElement * frames = doc.NewElement("frames"); frames->SetAttribute("n", xml->nFrames); for (int i = 0; i < (int)xml->frameNumber.size(); i++) { XMLElement * frame = doc.NewElement("frame"); frame->SetAttribute("id", xml->frameNumber[i]); frame->SetAttribute("laneCenter", xml->laneCenter[i]); frame->SetAttribute("laneChange", xml->laneChange[i]); frame->SetAttribute("laneLeft", xml->multipleLanes.left[i]); frame->SetAttribute("laneRight", xml->multipleLanes.right[i]); frame->SetAttribute("lmtLeft", xml->lmt.left[i]); frame->SetAttribute("lmtRight", xml->lmt.right[i]); string roadSigns = ""; for (unsigned int j = 0; j < xml->roadSigns[i].size(); j++) { roadSigns += to_string(xml->roadSigns[i][j]); if (j != xml->roadSigns[i].size() - 1) roadSigns += ";"; } frame->SetAttribute("roadSigns", roadSigns.c_str()); frame->SetAttribute("time", xml->time[i]); XMLElement * position = doc.NewElement("position"); XMLElement * posLeft = doc.NewElement("left"); XMLElement * p1left = doc.NewElement("p1"); XMLElement * p2left = doc.NewElement("p2"); XMLElement * p3left = doc.NewElement("p3"); XMLElement * p4left = doc.NewElement("p4"); if (std::isnan(xml->position.left[i][0])) p1left->SetText("nan"); else p1left->SetText(xml->position.left[i][0]); if (std::isnan(xml->position.left[i][1])) p2left->SetText("nan"); else p2left->SetText(xml->position.left[i][1]); if (std::isnan(xml->position.left[i][2])) p3left->SetText("nan"); else p3left->SetText(xml->position.left[i][2]); if (std::isnan(xml->position.left[i][3])) p4left->SetText("nan"); else p4left->SetText(xml->position.left[i][3]); XMLElement * posRight = doc.NewElement("right"); XMLElement * p1right = doc.NewElement("p1"); XMLElement * p2right = doc.NewElement("p2"); XMLElement * p3right = doc.NewElement("p3"); XMLElement * p4right = doc.NewElement("p4"); if (std::isnan(xml->position.right[i][0])) p1right->SetText("nan"); else p1right->SetText(xml->position.right[i][0]); if (std::isnan(xml->position.right[i][1])) p2right->SetText("nan"); else p2right->SetText(xml->position.right[i][1]); if (std::isnan(xml->position.right[i][2])) p3right->SetText("nan"); else p3right->SetText(xml->position.right[i][2]); if (std::isnan(xml->position.right[i][3])) p4right->SetText("nan"); else p4right->SetText(xml->position.right[i][3]); // insert the elements posLeft->InsertEndChild(p1left); posLeft->InsertEndChild(p2left); posLeft->InsertEndChild(p3left); posLeft->InsertEndChild(p4left); posRight->InsertEndChild(p1right); posRight->InsertEndChild(p2right); posRight->InsertEndChild(p3right); posRight->InsertEndChild(p4right); position->InsertFirstChild(posLeft); position->InsertEndChild(posRight); frame->InsertFirstChild(position); frames->InsertEndChild(frame); } testInput->InsertEndChild(frames); doc.InsertFirstChild(testInput); // print to console: // XMLPrinter printer; // doc.Print(&printer); // cout << printer.CStr() << endl; doc.SaveFile(path.c_str()); return true; }