void XMLElement::Display() const { cout << "<" << value; const XMLAttribute* attrib = NULL; for ( attrib = attributes.First_Const(); attrib; attrib = attrib->Next_Const() ) { cout << " "; attrib->Display(); } XMLNode* node = NULL; if ( firstChild ) { cout << ">"; for ( node = firstChild; node; node=node->NextSibling() ) { node->Display( ); } cout << "</" << value << ">"; } else { cout << " />"; } }
void Arena::readXMLArena(const char* path){ cout << "Reading arena at: " << path << endl; XMLDocument doc; doc.LoadFile(path); XMLNode* svgObjs = doc.FirstChildElement("svg")->FirstChild(); while(svgObjs != NULL){ XMLElement * obj = svgObjs->ToElement(); if(strcmp(obj->Attribute("id"),"Arena") == 0){ this->arena = Rect( atof(obj->Attribute("x")), atof(obj->Attribute("y")), atof(obj->Attribute("width")), atof(obj->Attribute("height")), obj->Attribute("fill"), atof(obj->Attribute("stroke-width")), obj->Attribute("stroke"), obj->Attribute("id")); } if(strcmp(obj->Attribute("id"),"PostoAbastecimento") == 0){ this->postoAbastecimento = Rect( atof(obj->Attribute("x")), atof(obj->Attribute("y")), atof(obj->Attribute("width")), atof(obj->Attribute("height")), obj->Attribute("fill"), atof(obj->Attribute("stroke-width")), obj->Attribute("stroke"), obj->Attribute("id")); } if(strcmp(obj->Attribute("id"),"Jogador") == 0){ this->jogador = Circle( atof(obj->Attribute("cx")), atof(obj->Attribute("cy")), atof(obj->Attribute("r")), obj->Attribute("fill"), obj->Attribute("id")); } if(strcmp(obj->Attribute("id"),"Inimigo") == 0){ this->inimigos.push_back(Circle( atof(obj->Attribute("cx")), atof(obj->Attribute("cy")), atof(obj->Attribute("r")), obj->Attribute("fill"), obj->Attribute("id"))); } if(strcmp(obj->Attribute("id"),"ObjetoResgate") == 0){ this->objetosResgate.push_back(Circle( atof(obj->Attribute("cx")), atof(obj->Attribute("cy")), atoi(obj->Attribute("r")), obj->Attribute("fill"), obj->Attribute("id"))); } svgObjs = svgObjs->NextSibling(); } cout << "OK!" << endl; }
//----------------------------------------------------------------------- void ConverterPass1::XmlAnnotation(XMLElement *annotation, bool startUnit) { if (!annotation) return; if (startUnit) units_->push_back(Unit(bodyType_, Unit::ANNOTATION, 0, -1)); XmlAddId(annotation); for (XMLNode *ch = annotation->FirstChild(); ch; ch = ch->NextSibling()) { //<p>, <poem>, <cite>, <subtitle>, <empty-line>, <table> const char *tag = ch->Value(); if (!tag) continue; if (strcmp(tag, "p") == 0) p(); else if (strcmp(tag, "poem") == 0) poem(); else if (strcmp(tag, "cite") == 0) cite(); else if (strcmp(tag, "subtitle") == 0) subtitle(); else if (strcmp(tag, "empty-line") == 0) ; // do nothing here, was: empty_line(); else if (strcmp(tag, "table") == 0) table(); //</p>, </poem>, </cite>, </subtitle>, </empty-line>, </table> } }
void XMLDoc::ToFile(FILE *file,int blankdepth) { XMLNode* nodetemp = NULL; for ( nodetemp=FirstChild(); nodetemp; nodetemp=nodetemp->NextSibling() ) { nodetemp->ToFile( file, blankdepth ); fprintf_s( file, "\n" ); } }
int CSettings::ParseOutputs(XMLElement *Outputs) { // Parse Outputs XMLElement *Output = Outputs->FirstChildElement("output"); int NumberOfOutputs = 0; while(Output) { OutputContainer OutputParse; NumberOfOutputs++; if(!Output->Attribute("name")) { Log.error("Output entry has no name\n"); return false; } // Check if there is a duplicate name OutputParse.name = Output->Attribute("name"); for(list<OutputContainer>::iterator i=OutputsDB.begin(); i != OutputsDB.end(); ++i) { if(OutputParse.name.compare((*i).name) == 0) { Log.error("Duplicate output name [%s]\n", OutputParse.name.c_str()); return false; } } OutputParse.type = Output->Attribute("type"); XMLNode *OutSettings = Output->FirstChild(); while(OutSettings) { if(OutSettings->Value() && OutSettings->ToElement()->GetText()) { OutputParse.settings[OutSettings->Value()] = OutSettings->ToElement()->GetText(); Log.debug("parsed [%s]=[%s]", OutSettings->Value(), OutputParse.settings[OutSettings->Value()].c_str()); } OutSettings = OutSettings->NextSibling(); } OutputsDB.push_back(OutputParse); Output = Output->NextSiblingElement("output"); } Log.log("Parsed %d outputs\n", NumberOfOutputs); return true; }
bool AudioResourceManager::initialize() { srand(time(NULL)); Ogre::String path = Ogre::macBundlePath() + "/Contents/Resources/media/config/audio_events.xml"; //xml_document<> doc; // character type defaults to char FILE *audioConfigFile = fopen(path.data(), "r"); std::vector<char> buffer; int c; while (EOF !=(c=getc(audioConfigFile))){ buffer.push_back(c); } char buf[buffer.size()]; for (int i = 0; i < buffer.size(); i++){ buf[i] = buffer[i]; } XMLDocument doc; doc.Parse(buf); XMLElement *eventIter = doc.FirstChildElement()->FirstChildElement(); unsigned int currentHandle = 0; while (eventIter != NULL) { XMLNode *unitIter = eventIter->FirstChildElement()->NextSiblingElement(); std::string eventName = eventIter->FirstChildElement()->GetText(); while (unitIter != NULL) { AudioResource unit; unit.filename = unitIter->FirstChildElement("filename")->GetText();// first_node("filename")->value(); printf("filename: %s\n", unit.filename.c_str()); unit.panning = atof(unitIter->FirstChildElement("panning")->GetText()); unit.pitch = atof(unitIter->FirstChildElement("pitch")->GetText()); unit.looping = atoi(unitIter->FirstChildElement("looping")->GetText()); unit.gain = atof(unitIter->FirstChildElement("gain")->GetText()); unit.bufferHandle = -1; unit.sourceHandle = -1; if ( eventName == "apply_force_left" || eventName == "apply_force_right" || eventName=="fall_off") unit.canStop = false; else unit.canStop = true; alGenSources(1, &unit.sourceHandle); resources[eventName].push_back(unit); unitIter = unitIter->NextSibling(); } eventIter = eventIter->NextSiblingElement(); } return true; }
//来自:TinyXML void XMLElement::ToFile(FILE *file,int blankdepth) { int i; for ( i = 0; i < blankdepth; i++ ) { fprintf( file, " " ); } fprintf_s( file, "<%s", value.c_str() ); XMLAttribute* attri = NULL; for ( attri = attributes.First(); attri; attri = attri->Next() ) { fprintf_s( file, " " ); attri->ToFile( file, blankdepth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. if ( !firstChild ) { fprintf_s( file, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf_s( file, ">" ); firstChild->ToFile( file, blankdepth + 1 ); fprintf_s( file, "</%s>", value.c_str() ); } else { XMLNode* node = NULL; fprintf_s( file, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf_s( file, "\n" ); } node->ToFile( file, blankdepth + 1 ); } fprintf_s( file, "\n" ); for( i=0; i < blankdepth; ++i ) fprintf_s( file, " " ); fprintf_s( file, "</%s>", value.c_str() ); } }
//----------------------------------------------------------------------------- XMLElement* XmlHelper::getChild(XMLNode *elm, Str8 tagName) { XMLNode* child = NULL; XMLElement* child_elm = NULL; if (elm) { for( child = elm->FirstChild(); child; child = child->NextSibling() ) { child_elm = child->ToElement(); if ( tagName==XML_GET_VALUE(child_elm) ) { return child_elm; } } } return NULL; }
//----------------------------------------------------------------------------- XMLElement* XmlHelper::getChild(XMLNode *elm, Str8 tagName, Str8 attr, Str8 attrName) { XMLNode* child = NULL; XMLElement* child_elm = NULL; Str8 childAttr; if (elm) { for( child = elm->FirstChild(); child; child = child->NextSibling() ) { child_elm = child->ToElement(); if ( tagName==XML_GET_VALUE(child_elm) ) { getAttribute(child_elm,childAttr,attrName); if ( childAttr == attr ) return child_elm; } } } return NULL; }
//----------------------------------------------------------------------------- UInt XmlHelper::getChildCount(XMLNode *elm) { XMLNode* currNode = elm->FirstChild(); XMLNode* firstSiblingNode = currNode; XMLNode* nextNode = NULL; UInt count = 0; while( currNode ) { //@ parallel nextNode = currNode->NextSibling(); if (nextNode&&nextNode==firstSiblingNode) { break; } currNode = nextNode; count ++; } return count; }
void XMLConfig::readXML(const char* path){ XMLDocument doc; cout << "Reading file at: " << path << endl; doc.LoadFile(path); // arquivosDeEntrada XMLElement* arquivosDeEntrada = doc.FirstChildElement("aplicacao")->FirstChildElement("arquivosDeEntrada"); XMLNode* arquivo = arquivosDeEntrada->FirstChild(); while(arquivo != NULL){ XMLElement* arq = arquivo->ToElement(); if(strcmp(arq->Name(),"arquivoDaArena") == 0){ this->arena = File(arq->Attribute("nome"), arq->Attribute("caminho"), arq->Attribute("tipo")); } arquivo = arquivo->NextSibling(); } cout << "OK!"<<endl; }
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 CSettings::ParseInputs(XMLElement *Inputs) { // Parse Inputs XMLElement *Input = Inputs->FirstChildElement("input"); int NumberOfInputs = 0; while(Input) { InputContainer InputParse; NumberOfInputs++; if(!Input->Attribute("type") || !Input->Attribute("UUID")) return false; InputParse.uuid = Input->Attribute("UUID"); InputParse.type = Input->Attribute("type"); XMLElement *Interface = Input->FirstChildElement("iface"); if(!Interface || !Interface->Attribute("type")) return false; InputParse.iface = Interface->Attribute("type"); XMLNode *iSets = Interface->FirstChild(); while(iSets) { if(iSets->Value() || iSets->ToElement()->GetText()) { InputParse.ifaceSettings[iSets->Value()] = iSets->ToElement()->GetText(); Log.debug("parsed [%s]=[%s]", iSets->Value(), InputParse.ifaceSettings[iSets->Value()].c_str()); } iSets = iSets->NextSibling(); } XMLElement *Sensor = Input->FirstChildElement("sensors")->FirstChildElement("sensor"); int NumOfSensors = 0; while(Sensor) { if(!Sensor->Attribute("address")) return false; NumOfSensors++; InputParse.sensors.push_back(atol(Sensor->Attribute("address"))); Sensor = Sensor->NextSiblingElement("sensor"); } XMLElement *Output = Input->FirstChildElement("output"); if(!Output || !Output->Attribute("name")) return false; InputParse.output = Output->Attribute("name"); if(Output->Attribute("cache")) InputParse.cache = Output->Attribute("cache"); else Log.warn("No cache db set. This is not recommended\n"); InputsDB.push_back(InputParse); Log.debug("Parsed %s (%s - %s) with %d sensors\n", InputParse.uuid.c_str(), InputParse.type.c_str(), InputParse.iface.c_str(), NumOfSensors); Input = Input->NextSiblingElement("input"); } Log.debug("Parsed %d inputs\n", NumberOfInputs); return true; }
int main() { // CURL* curl; //our curl object // // struct BufferStruct output; // Create an instance of out BufferStruct to accept LCs output // output.buffer = NULL; // output.size = 0; // // curl_global_init(CURL_GLOBAL_ALL); //pretty obvious // curl = curl_easy_init(); // // curl_easy_setopt(curl, CURLOPT_URL, "http://www.findyourfate.com/rss/horoscope-astrology-feed.asp?mode=view&todate=8/20/2015"); // curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteMemoryCallback); // curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&output); // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //tell curl to output its progress // // curl_easy_perform(curl); // curl_easy_cleanup(curl); // // FILE * fp; // fp = fopen( "example.xml","w"); // cout<<"HEILL!"; // if( !fp ) // return 1; // fprintf(fp, output.buffer ); // fclose( fp ); // // if( output.buffer ) // { // free ( output.buffer ); // output.buffer = 0; // output.size = 0; // } // // cin.get(); XMLDocument doc; doc.LoadFile("example.xml"); cout<< "ERROR ID: "<<doc.ErrorName()<<endl; XMLNode * pRoot = doc.FirstChild(); if (pRoot ==NULL) cout<<"ERROR!!!"<<endl; XMLNode* SiblingNode = pRoot->NextSibling(); XMLNode* ChildNode = SiblingNode->FirstChild(); XMLElement *ChildElmt = ChildNode->ToElement(); string strTagName = ChildElmt->Name(); cout<<strTagName<<endl; XMLNode* Child_2_Node = ChildNode->FirstChild(); XMLElement *Child_2_NodeElmt = Child_2_Node->ToElement(); strTagName = Child_2_NodeElmt->Name(); cout<<strTagName<<endl; strTagName = Child_2_NodeElmt->GetText(); cout<<strTagName<<endl; XMLNode* secSibling = Child_2_Node->NextSibling(); XMLElement *Sib_2_NodeElmt = secSibling->ToElement(); strTagName = Sib_2_NodeElmt->Name(); cout<<strTagName<<endl; strTagName = Sib_2_NodeElmt->GetText(); cout<<strTagName<<endl; //XMLElement* pElement = pRoot->ToElement(); //if (pElement ==NULL) // cout<<"ERROR"<<endl; // XMLElement * pElement = pRoot->FirstChildElement("rss")->FirstChildElement("channel"); // if (pElement ==NULL) // cout<<"ERROR"<<endl; // if (pElement ==NULL) // cout<<"ERROR"<<endl; // const char* title = pElement->GetText(); // printf( "Name of play (1): %s\n", title ); // cout << endl << pElement->GetText() << endl; //cin.get(); //curl_global_cleanup(); return 0; }
PluginChipFactory::PluginChipFactory() { XMLDocument doc; FILE * f = fopen("atanua.xml", "rb"); if (doc.LoadFile(f)) { fclose(f); return; } fclose(f); // Load config XMLNode *root; for (root = doc.FirstChild(); root != 0; root = root->NextSibling()) { if (root->ToElement()) { if (stricmp(root->Value(), "AtanuaConfig")==0) { XMLNode *part; for (part = root->FirstChild(); part != 0; part = part->NextSibling()) { if (part->ToElement()) { if (stricmp(part->Value(), "Plugin") == 0) { const char *dll = ((XMLElement*)part)->Attribute("dll"); DLLHANDLETYPE h = opendll(dll); if (h) { getatanuadllinfoproc getdllinfo = (getatanuadllinfoproc)getdllproc(h, "getatanuadllinfo"); if (getdllinfo) { atanuadllinfo *dllinfo = new atanuadllinfo; getdllinfo(dllinfo); if (dllinfo->mDllVersion <= ATANUA_PLUGIN_DLL_VERSION) { mDllInfo.push_back(dllinfo); mDllHandle.push_back(h); } else { char temp[512]; sprintf(temp, "Plug-in \"%s\" version is incompatible \n" "with the current version of Atanua.\n" "\n" "Try to use it anyway?", dll); if (okcancel(temp)) { mDllInfo.push_back(dllinfo); mDllHandle.push_back(h); } } } } } } } } } } }
bool FractalConfiguration::open(string filename) { if(invalidID()) return true; m_dirty = false; XMLDocument doc; // Parse file doc.LoadFile(filename.c_str()); if(doc.Error()) { m_last_error = doc.GetErrorStr1(); return true; } // Get data XMLElement *root = doc.RootElement(); string name = string(root->Name()); if(name != "fractal") { m_last_error = "Configuration file is invalid!"; return true; } if(root->Attribute("id", m_id.c_str())) { XMLNode *node = root->FirstChild(); // Loop over all properties while(node != NULL) { XMLElement *element = node->ToElement(); if(element == NULL) { m_last_error = "Configuration file is invalid!"; return true; } // Get name and type (attributes) const char* tmp_name = element->Attribute("name"); const char* tmp_type = element->Attribute("type"); if(tmp_name == NULL || tmp_type == NULL) { m_last_error = "Configuration file is invalid!"; return true; } string name(tmp_name); string type(tmp_type); // Get text const char* tmp_text = element->GetText(); string text = ""; if(tmp_text != NULL) text = tmp_text; // Set property if(type == "string") { if(setStringProperty(name, text)) return true; } else if(type == "int") { int value; if(stringToInt(text, &value)) { m_last_error = "Error in configuration: " + text + " should be an integer"; return true; } if(setIntProperty(name, value)) return true; } else if(type == "double") { double value; if(stringToDouble(text, &value)) { m_last_error = "Error in configuration: " + text + " should be a double"; return true; } if(setDoubleProperty(name, value)) return true; } else if(type == "bool") { bool value; if(text == "1") value = true; else if(text == "0") value = false; else { m_last_error = "Error in configuration: " + text + " should be boolean (0 or 1)"; return true; } if(setBoolProperty(name, value)) return true; } else { m_last_error = "Error in configuration: " + type + " is not a valid type"; return true; } // Next node node = node->NextSibling(); } } else { m_last_error = "File contains not the configuration of a fractal with ID " + m_id; return true; } resetDirty(); return false; }
int main() { bool soundFlag = false; std::string headlines[3000]; int strCount = 0; bool storyExists = false; int pageSwitch = 0; while (true){ std::ofstream a_file ( "ESPN_NEWS.txt", std::ios::app ); CURL *curl; FILE *fp; CURLcode res; if (pageSwitch==0){ char *url = "http://sports.espn.go.com/espn/rss/news"; char outfilename[FILENAME_MAX] = "input3.xml"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } } else if(pageSwitch==1){ char *url = "http://sports.espn.go.com/espn/rss/nfl/news"; char outfilename[FILENAME_MAX] = "input3.xml"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } } else if(pageSwitch==2){ char *url = "http://sports.espn.go.com/espn/rss/nba/news"; char outfilename[FILENAME_MAX] = "input3.xml"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } } else{ char *url = "http://sports.espn.go.com/espn/rss/espnu/news"; char outfilename[FILENAME_MAX] = "input3.xml"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } } //////////////////////////////////////////////////////////////// bool loopFlag = true; bool bigLoop = true; tinyxml2::XMLDocument doc; doc.LoadFile( "input3.xml" ); XMLNode *rootnode = doc.FirstChild(); ////////////////////////////// rootnode = rootnode->NextSibling(); rootnode = rootnode->FirstChild();////////////hard code to get past the xml header into <ITEM> </ITEM portion rootnode = rootnode->FirstChild(); rootnode = rootnode->NextSibling(); /////////////////////////////////// while(loopFlag==true){ if(std::strcmp(rootnode->Value(),"item") != 0){ rootnode = rootnode->NextSibling(); } else loopFlag=false; } while(bigLoop==true){ XMLHandle safe = rootnode; if(safe.ToNode()==NULL) bigLoop=false; else{ NewsEntry *story = new NewsEntry(); rootnode = rootnode->FirstChild(); rootnode = rootnode->NextSibling(); rootnode = rootnode->FirstChild(); story->setTitle(rootnode->Value()); for(int x=0; x<strCount; x++){ if(story->getTitle().compare(headlines[x])==0){ storyExists = true; } } if(storyExists==false){ if(soundFlag==true){ PlaySound(TEXT("sportscenter.wav"), NULL, SND_FILENAME | SND_ASYNC); } std::cout<< story->getTitle() <<std::endl; a_file << story->getTitle(); a_file << "\n"; headlines[strCount] = story->getTitle(); strCount++; } rootnode = rootnode->Parent(); rootnode = rootnode->NextSibling(); rootnode = rootnode->FirstChild(); story->setDescription(rootnode->Value()); if(storyExists==false){ std::cout<< story->getDescription() <<std::endl; a_file << story->getDescription(); a_file << "\n"; } rootnode = rootnode->Parent(); rootnode = rootnode->NextSibling(); rootnode = rootnode->FirstChild(); story->setPubDate(rootnode->Value()); if(storyExists==false){ std::cout << story->getPubdate() <<std::endl; a_file << story->getPubdate(); a_file << "\n"; } rootnode = rootnode->Parent(); rootnode = rootnode->NextSibling(); rootnode = rootnode->FirstChild(); story->setLink(rootnode->Value()); if(storyExists==false){ //std::cout<< story->getLink() << std::endl; a_file << story->getLink(); a_file << "\n"; a_file << "\n"; printf("\n"); } rootnode = rootnode->Parent(); rootnode = rootnode->Parent(); rootnode = rootnode->NextSibling(); delete story; storyExists = false; } } pageSwitch++; if(pageSwitch>3){ pageSwitch = 0; soundFlag=true; } a_file.close(); Sleep(100000); } return 0; }
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; }
void AtanuaConfig::load() { XMLDocument doc; XMLDeclaration *pDec; XMLElement *pRoot; XMLElement *pElement; FILE * f = fopen("atanua.xml", "rb"); if (!f) { // Save config pDec = doc.NewDeclaration(); doc.InsertEndChild(pDec); pRoot = doc.NewElement("AtanuaConfig"); pRoot->SetAttribute("GeneratedWith",TITLE); doc.InsertEndChild(pRoot); pElement = doc.NewElement("PropagateInvalidState"); pElement->SetAttribute("value", mPropagateInvalidState == PINSTATE_PROPAGATE_INVALID); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("CustomCursors"); pElement->SetAttribute("value", mCustomCursors); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("PerformanceIndicators"); pElement->SetAttribute("value", mPerformanceIndicators); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("SwapShiftAndCtrl"); pElement->SetAttribute("value", mSwapShiftAndCtrl); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("WireFry"); pElement->SetAttribute("value", mWireFry); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("AudioEnable"); pElement->SetAttribute("value", mAudioEnable); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("ToolkitWidth"); pElement->SetAttribute("value", mToolkitWidth); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("MaxPhysicsMs"); pElement->SetAttribute("value", mMaxPhysicsMs); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("InitialWindow"); pElement->SetAttribute("width", mWindowWidth); pElement->SetAttribute("height", mWindowHeight); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("TooltipDelay"); pElement->SetAttribute("value", mTooltipDelay); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("LinePickTolerance"); pElement->SetAttribute("value", mLinePickTolerance); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("LineEndTolerance"); pElement->SetAttribute("value", mLineEndTolerance); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("LineSplitDragDistance"); pElement->SetAttribute("value", mLineSplitDragDistance); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("ChipCloneDragDistance"); pElement->SetAttribute("value", mChipCloneDragDistance); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("User"); pElement->SetAttribute("name", "[No user name set]"); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("FontSystem"); pElement->SetAttribute("CacheKeys", mFontCacheMax); pElement->SetAttribute("VBO", mUseVBOs); pElement->SetAttribute("SafeMode", mUseOldFontSystem); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("PerformanceOptions"); pElement->SetAttribute("Blending", mUseBlending); pElement->SetAttribute("AntialiasedLines", mAntialiasedLines); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("Limits"); pElement->SetAttribute("MaxBoxes", mMaxActiveBoxes); pElement->SetAttribute("PhysicsKHz", mPhysicsKHz); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("LED"); pElement->SetAttribute("Samples", mLEDSamples); pRoot->InsertEndChild(pElement); pElement = doc.NewElement("Autosave"); pElement->SetAttribute("Directory", ""); pElement->SetAttribute("Enable", "0"); pElement->SetAttribute("SaveCount", "10"); pElement->SetAttribute("Interval", "1"); pRoot->InsertEndChild(pElement); f = fopen("atanua.xml", "wb"); doc.SaveFile(f); fclose(f); } else { if (doc.LoadFile(f)) { fclose(f); return; } fclose(f); // Load config XMLNode *root; for (root = doc.FirstChild(); root != 0; root = root->NextSibling()) { if (root->ToElement()) { if (stricmp(root->Value(), "AtanuaConfig")==0) { XMLNode *part; for (part = root->FirstChild(); part != 0; part = part->NextSibling()) { if (part->ToElement()) { if (stricmp(part->Value(), "FontSystem") == 0) { ((XMLElement*)part)->QueryIntAttribute("CacheKeys", &mFontCacheMax); ((XMLElement*)part)->QueryIntAttribute("VBO", &mUseVBOs); ((XMLElement*)part)->QueryIntAttribute("SafeMode", &mUseOldFontSystem); } else if (stricmp(part->Value(), "PerformanceOptions") == 0) { ((XMLElement*)part)->QueryIntAttribute("AntialiasedLines", &mAntialiasedLines); ((XMLElement*)part)->QueryIntAttribute("Blending", &mUseBlending); } else if (stricmp(part->Value(), "PropagateInvalidState") == 0) { int propagate; ((XMLElement*)part)->QueryIntAttribute("value", &propagate); if (propagate) mPropagateInvalidState = PINSTATE_PROPAGATE_INVALID; else mPropagateInvalidState = PINSTATE_HIGHZ; } else if (stricmp(part->Value(), "CustomCursors") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mCustomCursors); } else if (stricmp(part->Value(), "PerformanceIndicators") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mPerformanceIndicators); } else if (stricmp(part->Value(), "SwapShiftAndCtrl") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mSwapShiftAndCtrl); } else if (stricmp(part->Value(), "WireFry") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mWireFry); } else if (stricmp(part->Value(), "AudioEnable") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mAudioEnable); } else if (stricmp(part->Value(), "ToolkitWidth") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mToolkitWidth); } else if (stricmp(part->Value(), "MaxPhysicsMs") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mMaxPhysicsMs); } else if (stricmp(part->Value(), "InitialWindow") == 0) { ((XMLElement*)part)->QueryIntAttribute("width", &mWindowWidth); ((XMLElement*)part)->QueryIntAttribute("height", &mWindowHeight); } else if (stricmp(part->Value(), "TooltipDelay") == 0) { ((XMLElement*)part)->QueryIntAttribute("value", &mTooltipDelay); } else if (stricmp(part->Value(), "LinePickTolerance") == 0) { ((XMLElement*)part)->QueryFloatAttribute("value", &mLinePickTolerance); } else if (stricmp(part->Value(), "LineEndTolerance") == 0) { ((XMLElement*)part)->QueryFloatAttribute("value", &mLineEndTolerance); } else if (stricmp(part->Value(), "LineSplitDragDistance") == 0) { ((XMLElement*)part)->QueryFloatAttribute("value", &mLineSplitDragDistance); } else if (stricmp(part->Value(), "ChipCloneDragDistance") == 0) { ((XMLElement*)part)->QueryFloatAttribute("value", &mChipCloneDragDistance); } else if (stricmp(part->Value(), "Limits") == 0) { ((XMLElement*)part)->QueryIntAttribute("MaxBoxes", &mMaxActiveBoxes); ((XMLElement*)part)->QueryIntAttribute("PhysicsKHz", &mPhysicsKHz); } else if (stricmp(part->Value(), "LED") == 0) { ((XMLElement*)part)->QueryIntAttribute("Samples", &mLEDSamples); if (mLEDSamples <= 0) mLEDSamples = 1; if (mLEDSamples > 10000) mLEDSamples = 10000; } else if (stricmp(part->Value(), "User") == 0) { const char *t = ((XMLElement*)part)->Attribute("name"); if (t && strlen(t) > 0) { delete[] mUserInfo; mUserInfo = mystrdup(t); } } if (stricmp(part->Value(), "Autosave") == 0) { ((XMLElement*)part)->QueryIntAttribute("Enable", &mAutosaveEnable); ((XMLElement*)part)->QueryIntAttribute("SaveCount", &mAutosaveCount); ((XMLElement*)part)->QueryIntAttribute("Interval", &mAutosaveInterval); const char * dir = ((XMLElement*)part)->Attribute("Directory"); if (dir) { int len = strlen(dir); if (dir[len] == '/' || dir[len] == '\\') { mAutosaveDir = mystrdup(dir); } else { char temp[1024]; sprintf(temp, "%s/", dir); mAutosaveDir = mystrdup(temp); } } else { mAutosaveDir = mystrdup(""); } } } } } } } } }
bool cSDL2DSceneManager::loadFromXMLFile(std::string Filename) { XMLDocument doc(Filename.c_str()); std::list<c2DLayer*> List; if(doc.LoadFile(Filename.c_str()) == XML_NO_ERROR) { //Find resources node XMLNode* ResourceTree = doc.RootElement(); if(ResourceTree) { //Enumerate resource objects for(XMLNode* child = ResourceTree->FirstChild(); child; child = child->NextSibling()) { XMLElement *Element = child->ToElement(); if(Element) { c2DLayer *Layer = new c2DLayer(); Layer->m_ZOrder = m_Layers.size(); for(XMLAttribute* ElementAttrib = const_cast<XMLAttribute*>(Element->FirstAttribute()); ElementAttrib; ElementAttrib = const_cast<XMLAttribute*>(ElementAttrib->Next())) { //Examine layers std::string AttribName = ElementAttrib->Name(); std::string AttribValue = ElementAttrib->Value(); //Detect resource type. Graphic? Audio? Text? if(AttribName=="name") { Layer->m_Name=AttribValue; continue; } if(AttribName=="posx") { Layer->m_PosX = atof(AttribValue.c_str()); } if(AttribName=="posy") { Layer->m_PosY = atof(AttribValue.c_str()); } if(AttribName=="visible") { if(AttribValue=="true") Layer->m_bVisible=true; else Layer->m_bVisible=false; } } m_Layers.push_back(Layer); //Cycle through layer objects for(XMLNode* objs = child->FirstChild(); objs; objs = objs->NextSibling()) { if(std::string(objs->Value())=="objects") { for(XMLNode* obj = objs->FirstChild(); obj; obj = obj->NextSibling()) { XMLElement *ObjElement = obj->ToElement(); addLayerObjects(Layer, ObjElement); } } } } } sortLayers(); return true; } } return false; }
void LevelParser::parseTileLayer(XMLElement* pTileElement, Level *pLevel) { // New TileLayer instance TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, TheGame::Instance().getTilesets()); // local temporary variable bool collidable = false; // A multidimensional array of int values to hold our final decoded and uncompressed tile data std::vector<std::vector<int>> data; // xml data node XMLElement* pDataNode = nullptr; // to store base64 decoded information std::string decodedIDs; // We search for the node we need for (XMLElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { // check if layer has properties if (e->Value() == std::string("properties")) { for (XMLElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement()) { if (property->Value() == std::string("property")) { // Check if it is a collision layer if (property->Attribute("name") == std::string("collidable")) { collidable = true; } } } } if (e->Value() == std::string("data")) { pDataNode = e; } } // Tile information not encoded nor compressed if (pDataNode->Attribute("encoding") == nullptr) { std::vector<int> layerRow(m_width); for (int rows = 0; rows < m_height; rows++) { data.push_back(layerRow); } XMLElement* tile = pDataNode->FirstChildElement(); int id; for (int rows = 0; rows < m_height; rows++) { for (int cols = 0; cols < m_width ; cols++) { tile->QueryAttribute("gid", &data[rows][cols]); tile = tile->NextSiblingElement(); } } } else { // We get the text (our encoded/compressed data) from the data node and use the base64 decoder to decode it for (XMLNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling()) { XMLText* text = e->ToText(); std::string t = text->Value(); decodedIDs = base64_decode(t); } // We use the zlib library to decompress our data once again uLongf sizeofids = m_width * m_height * sizeof(int); std::vector<unsigned> gids(sizeofids); uncompress((Bytef*)&gids[0], &sizeofids, (const Bytef*)decodedIDs.c_str(), decodedIDs.size()); // gids now contains all of our tile IDs, so we fill our data array with the correct values 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); pTileLayer->setMapWidth(m_width); // push into collision array and mark the layer as collidable if necessary if (collidable) { pTileLayer->setCollidable(true); pLevel->getCollisionLayers()->push_back(pTileLayer); } pLevel->getLayers()->push_back(pTileLayer); }