int main(int argc, char** argv) { if( argc < 2 ) return -1; TiXmlDocument* doc = loadFromFile(argv[1]); sofa::core::init(); int retValue = 0; if(doc ) { DiscoverNodes v_nodes; DiscoverDisplayFlagsVisitor v_displayFlags; doc->Accept(&v_nodes); doc->Accept(&v_displayFlags); for(unsigned int i=0; i < v_nodes.leaves.size(); ++i ) { createVisualStyleVisitor(v_nodes.leaves[i],v_displayFlags.map_displayFlags); } for( unsigned int i=0; i < v_nodes.nodes.size(); ++i) { removeShowAttributes(v_nodes.nodes[i]); } if( v_nodes.rootNode() ) { std::map<const TiXmlElement*,sofa::core::visual::DisplayFlags*>::iterator it_root; it_root = v_displayFlags.map_displayFlags.find(v_nodes.rootNode()); if( it_root != v_displayFlags.map_displayFlags.end() ) { DisplayFlags* root_flags = it_root->second; convert_false_to_neutral(*root_flags); TiXmlElement* visualStyle; if( ! root_flags->isNeutral() ) { if( (visualStyle = v_nodes.rootNode()->FirstChildElement("VisualStyle") ) == NULL ) { TiXmlElement* visualstyle = new TiXmlElement("VisualStyle"); std::ostringstream oss; oss << *root_flags; visualstyle->SetAttribute("displayFlags",oss.str()); TiXmlElement* first_child = v_nodes.rootNode()->FirstChildElement(); if(first_child) v_nodes.rootNode()->InsertBeforeChild(first_child,*visualstyle); else v_nodes.rootNode()->LinkEndChild(visualstyle); } else { std::ostringstream oss; oss << *root_flags; visualStyle->SetAttribute("displayFlags",oss.str()); } } else { if( (visualStyle = v_nodes.rootNode()->FirstChildElement("VisualStyle")) != NULL ) { v_nodes.rootNode()->RemoveChild(visualStyle); } } } } doc->Print(); std::cout.flush(); delete doc; } else { return -1; } sofa::core::cleanup(); return retValue; }
int main() { // // We start with the 'demoStart' todo list. Process it. And // should hopefully end up with the todo list as illustrated. // const char* demoStart = "<?xml version=\"1.0\" standalone='no' >\n" "<!-- Our to do list data -->" "<ToDo>\n" "<!-- Do I need a secure PDA? -->\n" "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>" "<Item priority=\"2\" distance='none'> Do bills </Item>" "<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>" "</ToDo>"; { #ifdef TIXML_USE_STL // What the todo list should look like after processing. // In stream (no formatting) representation. const char* demoEnd = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<!-- Our to do list data -->" "<ToDo>" "<!-- Do I need a secure PDA? -->" "<Item priority=\"2\" distance=\"close\">Go to the" "<bold>Toy store!" "</bold>" "</Item>" "<Item priority=\"1\" distance=\"far\">Talk to:" "<Meeting where=\"School\">" "<Attendee name=\"Marple\" position=\"teacher\" />" "<Attendee name=\"Voel\" position=\"counselor\" />" "</Meeting>" "<Meeting where=\"Lunch\" />" "</Item>" "<Item priority=\"2\" distance=\"here\">Do bills" "</Item>" "</ToDo>"; #endif // The example parses from the character string (above): #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &startMemState ); #endif { // Write to a file and read it back, to check file I/O. TiXmlDocument doc( "demotest.xml" ); doc.Parse( demoStart ); if ( doc.Error() ) { printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() ); exit( 1 ); } doc.SaveFile(); } TiXmlDocument doc( "demotest.xml" ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() ); exit( 1 ); } printf( "** Demo doc read from disk: ** \n\n" ); printf( "** Printing via doc.Print **\n" ); doc.Print( stdout ); { printf( "** Printing via TiXmlPrinter **\n" ); TiXmlPrinter printer; doc.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); } #ifdef TIXML_USE_STL { printf( "** Printing via operator<< **\n" ); std::cout << doc; } #endif TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChildElement(); // This skips the "PDA" comment. assert( node ); itemElement = node->ToElement(); assert( itemElement ); itemElement->SetAttribute( "priority", 2 ); // Change the distance to "doing bills" from // "none" to "here". It's the next sibling element. itemElement = itemElement->NextSiblingElement(); assert( itemElement ); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil Dinosaurs!" item. // It is 1 more sibling away. We ask the parent to remove // a particular child. itemElement = itemElement->NextSiblingElement(); todoElement->RemoveChild( itemElement ); itemElement = 0; // -------------------------------------------------------- // What follows is an example of created elements and text // nodes and adding them to the document. // -------------------------------------------------------- // Add some meetings. TiXmlElement item( "Item" ); item.SetAttribute( "priority", "1" ); item.SetAttribute( "distance", "far" ); TiXmlText text( "Talk to:" ); TiXmlElement meeting1( "Meeting" ); meeting1.SetAttribute( "where", "School" ); TiXmlElement meeting2( "Meeting" ); meeting2.SetAttribute( "where", "Lunch" ); TiXmlElement attendee1( "Attendee" ); attendee1.SetAttribute( "name", "Marple" ); attendee1.SetAttribute( "position", "teacher" ); TiXmlElement attendee2( "Attendee" ); attendee2.SetAttribute( "name", "Voel" ); attendee2.SetAttribute( "position", "counselor" ); // Assemble the nodes we've created: meeting1.InsertEndChild( attendee1 ); meeting1.InsertEndChild( attendee2 ); item.InsertEndChild( text ); item.InsertEndChild( meeting1 ); item.InsertEndChild( meeting2 ); // And add the node to the existing list after the first child. node = todoElement->FirstChild( "Item" ); assert( node ); itemElement = node->ToElement(); assert( itemElement ); todoElement->InsertAfterChild( itemElement, item ); printf( "\n** Demo doc processed: ** \n\n" ); doc.Print( stdout ); #ifdef TIXML_USE_STL printf( "** Demo doc processed to stream: ** \n\n" ); cout << doc << endl << endl; #endif // -------------------------------------------------------- // Different tests...do we have what we expect? // -------------------------------------------------------- int count = 0; TiXmlElement* element; ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL cout << "** Basic structure. **\n"; ostringstream outputStream( ostringstream::out ); outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), outputStream.str().c_str(), true ); #endif node = doc.RootElement(); assert( node ); XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Root element value is 'ToDo'.", "ToDo", node->Value()); node = node->FirstChild(); XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) ); node = node->NextSibling(); XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Value is 'Item'.", "Item", node->Value() ); node = node->FirstChild(); XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) ); XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() ); ////////////////////////////////////////////////////// printf ("\n** Iterators. **\n"); // Walk all the top level nodes of the document. count = 0; for( node = doc.FirstChild(); node; node = node->NextSibling() ) { count++; } XmlTest( "Top level nodes, using First / Next.", 3, count ); count = 0; for( node = doc.LastChild(); node; node = node->PreviousSibling() ) { count++; } XmlTest( "Top level nodes, using Last / Previous.", 3, count ); // Walk all the top level nodes of the document, // using a different syntax. count = 0; for( node = doc.IterateChildren( 0 ); node; node = doc.IterateChildren( node ) ) { count++; } XmlTest( "Top level nodes, using IterateChildren.", 3, count ); // Walk all the elements in a node. count = 0; for( element = todoElement->FirstChildElement(); element; element = element->NextSiblingElement() ) { count++; } XmlTest( "Children of the 'ToDo' element, using First / Next.", 3, count ); // Walk all the elements in a node by value. count = 0; for( node = todoElement->FirstChild( "Item" ); node; node = node->NextSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count ); count = 0; for( node = todoElement->LastChild( "Item" ); node; node = node->PreviousSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count ); #ifdef TIXML_USE_STL { cout << "\n** Parsing. **\n"; istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '>' />" ); TiXmlElement element0( "default" ); parse0 >> element0; XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() ); XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" )); XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) ); XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) ); } #endif { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; TiXmlDocument docTest; docTest.Parse( error ); XmlTest( "Error row", docTest.ErrorRow(), 3 ); XmlTest( "Error column", docTest.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } #ifdef TIXML_USE_STL { ////////////////////////////////////////////////////// cout << "\n** Streaming. **\n"; // Round trip check: stream in, then stream back out to verify. The stream // out has already been checked, above. We use the output istringstream inputStringStream( outputStream.str() ); TiXmlDocument document0; inputStringStream >> document0; ostringstream outputStream0( ostringstream::out ); outputStream0 << document0; XmlTest( "Stream round trip correct.", string( demoEnd ).c_str(), outputStream0.str().c_str(), true ); std::string str; str << document0; XmlTest( "String printing correct.", string( demoEnd ).c_str(), str.c_str(), true ); } #endif } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); XmlTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE ); } { const char* str = "<doc/>"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal; double dVal; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetDoubleAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); XmlTest( "Attribute round trip. c-string.", "strValue", cStr ); XmlTest( "Attribute round trip. int.", 1, iVal ); XmlTest( "Attribute round trip. double.", -1, (int)dVal ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" "</room>"; TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); assert( docHandle.Node() ); assert( roomHandle.Element() ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 ); XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 ); XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" " <!-- Silly example -->\n" " <door wall='north'>A great door!</door>\n" "\t<door wall='east'/>" "</room>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild(); TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild(); TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 ); TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 ); assert( docHandle.Node() ); assert( roomHandle.Element() ); assert( commentHandle.Node() ); assert( textHandle.Text() ); assert( door0Handle.Element() ); assert( door1Handle.Element() ); TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration(); assert( declaration ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); TiXmlText* text = textHandle.Text(); TiXmlComment* comment = commentHandle.Node()->ToComment(); assert( comment ); TiXmlElement* door0 = door0Handle.Element(); TiXmlElement* door1 = door1Handle.Element(); XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 ); XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 ); XmlTest( "Location tracking: room row", room->Row(), 1 ); XmlTest( "Location tracking: room col", room->Column(), 45 ); XmlTest( "Location tracking: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: doors col", doors->Column(), 51 ); XmlTest( "Location tracking: Comment row", comment->Row(), 2 ); XmlTest( "Location tracking: Comment col", comment->Column(), 3 ); XmlTest( "Location tracking: text row", text->Row(), 3 ); XmlTest( "Location tracking: text col", text->Column(), 24 ); XmlTest( "Location tracking: door0 row", door0->Row(), 3 ); XmlTest( "Location tracking: door0 col", door0->Column(), 5 ); XmlTest( "Location tracking: door1 row", door1->Row(), 4 ); XmlTest( "Location tracking: door1 col", door1->Column(), 5 ); } // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "utf8testout.xml", "r" ); FILE* verify = fopen( "utf8testverify.xml", "r" ); //bool firstLineBOM=true; if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( /*!firstLineBOM && */ strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); okay = 0; break; } //firstLineBOM = false; } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else completely on non-wester machines, // which is why TinyXml is switching to UTF-8. const char latin[] = "<element>r\x82sum\x82</element>"; TiXmlDocument latinDoc; latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY ); text = latinDoc.FirstChildElement()->FirstChild()->ToText(); XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() ); } } ////////////////////// // Copy and assignment ////////////////////// printf ("\n** Copy and Assignment **\n"); { TiXmlElement element( "foo" ); element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN ); TiXmlElement elementCopy( element ); TiXmlElement elementAssign( "foo" ); elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN ); elementAssign = element; XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() ); XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() ); XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) ); TiXmlComment comment; comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN ); TiXmlComment commentCopy( comment ); TiXmlComment commentAssign; commentAssign = commentCopy; XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() ); XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() ); TiXmlUnknown unknown; unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlUnknown unknownCopy( unknown ); TiXmlUnknown unknownAssign; unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN ); unknownAssign = unknownCopy; XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() ); XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() ); TiXmlText text( "TextNode" ); TiXmlText textCopy( text ); TiXmlText textAssign( "incorrect" ); textAssign = text; XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() ); XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() ); TiXmlDeclaration dec; dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlDeclaration decCopy( dec ); TiXmlDeclaration decAssign; decAssign = dec; XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() ); XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() ); TiXmlDocument doc; elementCopy.InsertEndChild( textCopy ); doc.InsertEndChild( decAssign ); doc.InsertEndChild( elementCopy ); doc.InsertEndChild( unknownAssign ); TiXmlDocument docCopy( doc ); TiXmlDocument docAssign; docAssign = docCopy; #ifdef TIXML_USE_STL std::string original, copy, assign; original << doc; copy << docCopy; assign << docAssign; XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true ); XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true ); #endif } ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL printf ("\n** Parsing, no Condense Whitespace **\n"); TiXmlBase::SetCondenseWhiteSpace( false ); { istringstream parse1( "<start>This is \ntext</start>" ); TiXmlElement text1( "text" ); parse1 >> text1; XmlTest ( "Condense white space OFF.", "This is \ntext", text1.FirstChild()->Value(), true ); } TiXmlBase::SetCondenseWhiteSpace( true ); #endif ////////////////////////////////////////////////////// // GetText(); { const char* str = "<foo>This is text</foo>"; TiXmlDocument doc; doc.Parse( str ); const TiXmlElement* element = doc.RootElement(); XmlTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Clear(); doc.Parse( str ); element = doc.RootElement(); XmlTest( "GetText() contained element.", element->GetText() == 0, true ); str = "<foo>This is <b>text</b></foo>"; doc.Clear(); TiXmlBase::SetCondenseWhiteSpace( false ); doc.Parse( str ); TiXmlBase::SetCondenseWhiteSpace( true ); element = doc.RootElement(); XmlTest( "GetText() partial.", "This is ", element->GetText() ); } ////////////////////////////////////////////////////// // CDATA { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL //cout << doc << '\n'; doc.Clear(); istringstream parse0( str ); parse0 >> doc; //cout << doc << '\n'; XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); } { // [ 1482728 ] Wrong wide char parsing char buf[256]; buf[255] = 0; for( int i=0; i<255; ++i ) { buf[i] = (char)((i>=32) ? i : 32); } TIXML_STRING str( "<xmlElement><![CDATA[" ); str += buf; str += "]]></xmlElement>"; TiXmlDocument doc; doc.Parse( str.c_str() ); TiXmlPrinter printer; printer.SetStreamPrinting(); doc.Accept( &printer ); XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream iss( printer.Str() ); iss >> doc; std::string out; out << doc; XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true ); #endif } { // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags // CDATA streaming had a couple of bugs, that this tests for. const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream parse0( str ); parse0 >> doc; XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); } ////////////////////////////////////////////////////// // Visit() ////////////////////////////////////////////////////// printf( "\n** Fuzzing... **\n" ); const int FUZZ_ITERATION = 300; // The only goal is not to crash on bad input. int len = (int) strlen( demoStart ); for( int i=0; i<FUZZ_ITERATION; ++i ) { char* demoCopy = new char[ len+1 ]; strcpy( demoCopy, demoStart ); demoCopy[ i%len ] = (char)((i+1)*3); demoCopy[ (i*7)%len ] = '>'; demoCopy[ (i*11)%len ] = '<'; TiXmlDocument xml; xml.Parse( demoCopy ); delete [] demoCopy; } printf( "** Fuzzing Complete. **\n" ); ////////////////////////////////////////////////////// printf ("\n** Bug regression tests **\n"); // InsertBeforeChild and InsertAfterChild causes crash. { TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 ); XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true ); } { // InsertBeforeChild and InsertAfterChild causes crash. TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 ); XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true ); } // Reports of missing constructors, irregular string problems. { // Missing constructor implementation. No test -- just compiles. TiXmlText text( "Missing" ); #ifdef TIXML_USE_STL // Missing implementation: TiXmlDocument doc; string name = "missing"; doc.LoadFile( name ); TiXmlText textSTL( name ); #else // verifying some basic string functions: TiXmlString a; TiXmlString b( "Hello" ); TiXmlString c( "ooga" ); c = " World!"; a = b; a += c; a = a; XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() ); #endif } // Long filenames crashing STL version { TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" ); bool loadOkay = doc.LoadFile(); loadOkay = true; // get rid of compiler warning. // Won't pass on non-dev systems. Just a "no crash" check. //XmlTest( "Long filename. ", true, loadOkay ); } { // Entities not being written correctly. // From Lynn Allen const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright ©.\"> </psg>" "</passages>"; TiXmlDocument doc( "passages.xml" ); doc.Parse( passages ); TiXmlElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9."; XmlTest( "Entity transformation: read. ", expected, context, true ); FILE* textfile = fopen( "textfile.txt", "w" ); if ( textfile ) { psg->Print( textfile, 0 ); fclose( textfile ); } textfile = fopen( "textfile.txt", "r" ); assert( textfile ); if ( textfile ) { char buf[ 1024 ]; fgets( buf, 1024, textfile ); XmlTest( "Entity transformation: write. ", "<psg context=\'Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright \xC2\xA9.' />", buf, true ); } fclose( textfile ); } { FILE* textfile = fopen( "test5.xml", "w" ); if ( textfile ) { fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile); fclose(textfile); TiXmlDocument doc; doc.LoadFile( "test5.xml" ); XmlTest( "dot in element attributes and names", doc.Error(), 0); } } { FILE* textfile = fopen( "test6.xml", "w" ); if ( textfile ) { fputs("<element><Name>1.1 Start easy ignore fin thickness
</Name></element>", textfile ); fclose(textfile); TiXmlDocument doc; bool result = doc.LoadFile( "test6.xml" ); XmlTest( "Entity with one digit.", result, true ); TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XmlTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n" ); } } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; TiXmlDocument doc; doc.Parse( doctype ); doc.SaveFile( "test7.xml" ); doc.Clear(); doc.LoadFile( "test7.xml" ); TiXmlHandle docH( &doc ); TiXmlUnknown* unknown = docH.Child( 1 ).Unknown(); XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() ); #ifdef TIXML_USE_STL TiXmlNode* node = docH.Child( 2 ).Node(); std::string str; str << (*node); XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() ); #endif } { // [ 791411 ] Formatting bug // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; TiXmlDocument doc; doc.Parse( doctype ); TiXmlHandle docH( &doc ); TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment(); XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); #ifdef TIXML_USE_STL std::string str; str << (*comment); XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() ); #endif } { // [ 870502 ] White space issues TiXmlDocument doc; TiXmlText* text; TiXmlHandle docH( &doc ); const char* doctype0 = "<element> This has leading and trailing space </element>"; const char* doctype1 = "<element>This has internal space</element>"; const char* doctype2 = "<element> This has leading, trailing, and internal space </element>"; TiXmlBase::SetCondenseWhiteSpace( false ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading, trailing, and internal space ", text->Value() ); TiXmlBase::SetCondenseWhiteSpace( true ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Parsing repeated attributes.", true, doc.Error() ); // is an error to tinyxml (didn't use to be, but caused issues) //XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<ä>" "CöntäntßäöüÄÖÜ" "</ä>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() ); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // Bug [ 1195696 ] from marlonism TiXmlBase::SetCondenseWhiteSpace(false); TiXmlDocument xml; xml.Parse("<text><break/>This hangs</text>"); XmlTest( "Test safe error return.", xml.Error(), false ); } { // Bug [ 1243992 ] - another infinite loop TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); doc.Parse("<p><pb></pb>test</p>"); } { // Low entities TiXmlDocument xml; xml.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result ); xml.Print(); } { // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly TiXmlDocument xml; xml.Parse( "<foo attribute=bar\" />" ); XmlTest( "Throw error with bad end quotes.", xml.Error(), true ); } #ifdef TIXML_USE_STL { // Bug [ 1449463 ] Consider generic query TiXmlDocument xml; xml.Parse( "<foo bar='3' barStr='a string'/>" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; float f; bool b; std::string str; XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", (d==3.0), true ); XmlTest( "QueryValueAttribute", (i==3), true ); XmlTest( "QueryValueAttribute", (f==3.0f), true ); XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true ); } #endif #ifdef TIXML_USE_STL { // [ 1505267 ] redundant malloc in TiXmlElement::Attribute TiXmlDocument xml; xml.Parse( "<foo bar='3' />" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; std::string bar = "bar"; const std::string* atrrib = ele->Attribute( bar ); ele->Attribute( bar, &d ); ele->Attribute( bar, &i ); XmlTest( "Attribute", atrrib->empty(), false ); XmlTest( "Attribute", (d==3.0), true ); XmlTest( "Attribute", (i==3), true ); } #endif { // [ 1356059 ] Allow TiXMLDocument to only be at the top level TiXmlDocument xml, xml2; xml.InsertEndChild( xml2 ); XmlTest( "Document only at top level.", xml.Error(), true ); XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY ); } { // [ 1663758 ] Failure to report error on bad XML TiXmlDocument xml; xml.Parse("<x>"); XmlTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XmlTest("Missing end tag with trailing whitespace", xml.Error(), true); } { // [ 1635701 ] fail to parse files with a tag separated into two lines // I'm not sure this is a bug. Marked 'pending' for feedback. TiXmlDocument xml; xml.Parse( "<title><p>text</p\n><title>" ); //xml.Print(); //XmlTest( "Tag split by newline", xml.Error(), false ); } #ifdef TIXML_USE_STL { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; istringstream parse1( "<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); parse1 >> xml; TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } #endif { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } { TiXmlDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); int count = 0; TiXmlNode* ele = 0; while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) { ++count; } XmlTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; TiXmlDocument doc; doc.Parse( (const char*)buf); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. TiXmlDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XmlTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop TiXmlDocument xml; xml.Parse( "<infinite>loop" ); XmlTest( "Infinite loop test.", true, true ); } { // 1709904 - can not repro the crash { TiXmlDocument xml; xml.Parse( "<tag>/</tag>" ); XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" ); } /* Could not repro. { TiXmlDocument xml; xml.LoadFile( "EQUI_Inventory.xml" ); //XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" ); TiXmlPrinter printer; xml.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); }*/ } /* 1417717 experiment { TiXmlDocument xml; xml.Parse("<text>Dan & Tracie</text>"); xml.Print(stdout); } { TiXmlDocument xml; xml.Parse("<text>Dan &foo; Tracie</text>"); xml.Print(stdout); } */ #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
void CAdvancedSettings::ParseSettingsFile(const CStdString &file) { TiXmlDocument advancedXML; if (!CFile::Exists(file)) { CLog::Log(LOGNOTICE, "No settings file to load (%s)", file.c_str()); return; } if (!advancedXML.LoadFile(file)) { CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", file.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc()); return; } TiXmlElement *pRootElement = advancedXML.RootElement(); if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0) { CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", file.c_str()); return; } // succeeded - tell the user it worked CLog::Log(LOGNOTICE, "Loaded settings file from %s", file.c_str()); // Dump contents of AS.xml to debug log TiXmlPrinter printer; printer.SetLineBreak("\n"); printer.SetIndent(" "); advancedXML.Accept(&printer); CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", file.c_str(), printer.CStr()); TiXmlElement *pElement = pRootElement->FirstChildElement("audio"); if (pElement) { XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f); XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12); XMLUtils::GetString(pElement, "defaultplayer", m_audioDefaultPlayer); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0); XMLUtils::GetInt(pElement, "resample", m_musicResample, 0, 192000); TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps); pAudioExcludes = pElement->FirstChildElement("excludefromscan"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps); XMLUtils::GetString(pElement, "audiohost", m_audioHost); XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc); XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV); XMLUtils::GetFloat(pElement, "limiterhold", m_limiterHold, 0.0f, 100.0f); XMLUtils::GetFloat(pElement, "limiterrelease", m_limiterRelease, 0.001f, 100.0f); } pElement = pRootElement->FirstChildElement("karaoke"); if (pElement) { XMLUtils::GetFloat(pElement, "syncdelaycdg", m_karaokeSyncDelayCDG, -3.0f, 3.0f); // keep the old name for comp XMLUtils::GetFloat(pElement, "syncdelaylrc", m_karaokeSyncDelayLRC, -3.0f, 3.0f); XMLUtils::GetBoolean(pElement, "alwaysreplacegenre", m_karaokeChangeGenreForKaraokeSongs ); XMLUtils::GetBoolean(pElement, "storedelay", m_karaokeKeepDelay ); XMLUtils::GetInt(pElement, "autoassignstartfrom", m_karaokeStartIndex, 1, 2000000000); XMLUtils::GetBoolean(pElement, "nocdgbackground", m_karaokeAlwaysEmptyOnCdgs ); XMLUtils::GetBoolean(pElement, "lookupsongbackground", m_karaokeUseSongSpecificBackground ); TiXmlElement* pKaraokeBackground = pElement->FirstChildElement("defaultbackground"); if (pKaraokeBackground) { const char* attr = pKaraokeBackground->Attribute("type"); if ( attr ) m_karaokeDefaultBackgroundType = attr; attr = pKaraokeBackground->Attribute("path"); if ( attr ) m_karaokeDefaultBackgroundFilePath = attr; } } pElement = pRootElement->FirstChildElement("video"); if (pElement) { XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600); XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600); XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255); XMLUtils::GetString(pElement, "defaultplayer", m_videoDefaultPlayer); XMLUtils::GetString(pElement, "defaultdvdplayer", m_videoDefaultDVDPlayer); XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900); XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f); XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX); XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10); XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0); TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps); pVideoExcludes = pElement->FirstChildElement("excludefromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("cleanstrings"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps); XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp); XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint); XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc); XMLUtils::GetBoolean(pElement,"vdpauscaling",m_videoVDPAUScaling); XMLUtils::GetFloat(pElement, "nonlinearstretchratio", m_videoNonLinStretchRatio, 0.01f, 1.0f); XMLUtils::GetBoolean(pElement,"enablehighqualityhwscalers", m_videoEnableHighQualityHwScalers); XMLUtils::GetFloat(pElement,"autoscalemaxfps",m_videoAutoScaleMaxFps, 0.0f, 1000.0f); XMLUtils::GetBoolean(pElement,"allowmpeg4vdpau",m_videoAllowMpeg4VDPAU); XMLUtils::GetBoolean(pElement,"allowmpeg4vaapi",m_videoAllowMpeg4VAAPI); XMLUtils::GetBoolean(pElement, "disablebackgrounddeinterlace", m_videoDisableBackgroundDeinterlace); XMLUtils::GetInt(pElement, "useocclusionquery", m_videoCaptureUseOcclusionQuery, -1, 1); TiXmlElement* pAdjustRefreshrate = pElement->FirstChildElement("adjustrefreshrate"); if (pAdjustRefreshrate) { TiXmlElement* pRefreshOverride = pAdjustRefreshrate->FirstChildElement("override"); while (pRefreshOverride) { RefreshOverride override = {0}; float fps; if (XMLUtils::GetFloat(pRefreshOverride, "fps", fps)) { override.fpsmin = fps - 0.01f; override.fpsmax = fps + 0.01f; } float fpsmin, fpsmax; if (XMLUtils::GetFloat(pRefreshOverride, "fpsmin", fpsmin) && XMLUtils::GetFloat(pRefreshOverride, "fpsmax", fpsmax)) { override.fpsmin = fpsmin; override.fpsmax = fpsmax; } float refresh; if (XMLUtils::GetFloat(pRefreshOverride, "refresh", refresh)) { override.refreshmin = refresh - 0.01f; override.refreshmax = refresh + 0.01f;
HRESULT CAutotest::GetAutotestStatus(PVOID* ppvOutBuf, DWORD* pdwOutSize) { #define HV_XML_CMD_VERSION_NO "3.0" #define HVXML_VER "Ver" #define HVXML_HVCMD "HvCmd" #define HVXML_HVCMDRESPOND "HvCmdRespond" #define HVXML_RETCODE "RetCode" #define HVXML_RETMSG "RetMsg" #define HVXML_CMDNAME "CmdName" #define HVXML_RETURNLEN "RetLen" if (NULL == ppvOutBuf || NULL == pdwOutSize) { SW_TRACE_DEBUG("Err: NULL == ppvOutBuf || NULL == pdwOutSize\n"); return E_INVALIDARG; } if (!m_fInited) { SW_TRACE_DEBUG("Err: not inited yet!\n"); return E_NOTIMPL; } TiXmlDocument xmlOutDoc; TiXmlDeclaration *pDeclaration = NULL; TiXmlElement *pRootEle = NULL; pDeclaration = new TiXmlDeclaration("1.0","GB2312","yes"); if (NULL == pDeclaration) { SW_TRACE_DEBUG("Err: no memory for pDeclaration\n"); return E_OUTOFMEMORY; } xmlOutDoc.LinkEndChild(pDeclaration); pRootEle = new TiXmlElement(HVXML_HVCMDRESPOND); if (NULL == pRootEle) { SW_TRACE_DEBUG("Err: no memory for pRootEle\n"); return E_OUTOFMEMORY; } xmlOutDoc.LinkEndChild(pRootEle); pRootEle->SetAttribute(HVXML_VER, HV_XML_CMD_VERSION_NO); TiXmlElement *pReplyEle = new TiXmlElement(HVXML_CMDNAME); if (NULL == pReplyEle) { SW_TRACE_DEBUG("Err: no memory for pReplyEle\n"); return E_OUTOFMEMORY; } pRootEle->LinkEndChild(pReplyEle); TiXmlText * pReplyText = new TiXmlText("GetAutotestProgress"); if (NULL == pReplyText) { SW_TRACE_DEBUG("Err: no memory for pReplyText\n"); return E_OUTOFMEMORY; } pReplyEle->LinkEndChild(pReplyText); if (0 == m_dwTestProgress) { pReplyEle->SetAttribute(HVXML_RETCODE, 0); pReplyEle->SetAttribute(HVXML_RETMSG, "TestOK"); } else if (1 == m_dwTestProgress) { pReplyEle->SetAttribute(HVXML_RETCODE, 0); pReplyEle->SetAttribute(HVXML_RETMSG, "Testing"); } else if (2 == m_dwTestProgress) { pReplyEle->SetAttribute(HVXML_RETCODE, 0); pReplyEle->SetAttribute(HVXML_RETMSG, "TestFailed"); } else { pReplyEle->SetAttribute(HVXML_RETCODE, -1); pReplyEle->SetAttribute(HVXML_RETMSG, "GetAutotestProgress Failed"); } TiXmlPrinter xmlPrinter; xmlOutDoc.Accept(&xmlPrinter); *pdwOutSize = xmlPrinter.Size()+1; *ppvOutBuf = swpa_mem_alloc(*pdwOutSize); if (NULL == *ppvOutBuf) { SW_TRACE_DEBUG("Err: no memory for *ppvOutBuf!\n"); return E_OUTOFMEMORY; } swpa_memset(*ppvOutBuf, 0, *pdwOutSize); swpa_strncpy((CHAR*)*ppvOutBuf, xmlPrinter.CStr(), xmlPrinter.Size()); return S_OK; }
static int pack_body(TRANS& trans,std::string& body) { int ret = 0; gReader.fetchRow(); //生成交易流水号并记录 ret = GetNewRefno(trans.refno); if (ret) { return ret; } TiXmlDocument doc; { TiXmlElement root("ROOT"); doc.InsertEndChild(root); } char dt[15] = {0}; getsysdatetime(dt); string now(dt); TiXmlNode& root = *(doc.FirstChild()); //版本号 ec_add_xml_node_value(root,"VERSION", "010101" ); //交易代码 ec_add_xml_node_value(root,"TRANS_TYPE", "120226" ); //动作代码 ec_add_xml_node_value(root,"ACTION_TYPE", "1"); /*//响应代码 ec_add_xml_node_value(root,"RESP_CODE", );*/ //登录身份类型 ec_add_xml_node_value(root,"LOGIN_TYPE", "1"); //交易渠道 ec_add_xml_node_value(root,"TRANS_SOURCE", "BP"); //登录机构代码 ec_add_xml_node_value(root,"LOGIN_INST_CODE", "10006"); //交易日期 { string str; str.assign(trans.accdate,8); ec_add_xml_node_value(root,"TXN_DATE", str); } //交易时间 { string str; str.assign(trans.acctime,6); ec_add_xml_node_value(root,"TXN_TIME", str); } //跟踪号/流水号 { string str; str.assign(trans.refno,14); //str[6]='0'; //str[7]='0'; str=str.substr(6); //str.append(1,'1'); ec_add_xml_node_value(root,"TRACE_NO", str); } //受卡机终端标识码 ec_add_xml_node_value(root,"CARD_ACCPTR_TERMNL_ID", "12345676"); //登录网点代码 { string str; ret = get_ec_para(YTCEC_LOGIN_MERCH, str); if (ret) { LOG(ERROR, "中银通登录网点代码未配置"); return E_COMMON_ERR; } ec_add_xml_node_value(root,"LOGIN_MERCH_CODE", str); } //ec_add_xml_node_value(root,"LOGIN_MERCH_CODE", "J001"); //登录操作员代码 { string str; ret = get_ec_para(YTCEC_LOGIN_USER, str); if (ret) { LOG(ERROR, "中银通登录操作员代码未配置"); return E_COMMON_ERR; } ec_add_xml_node_value(root,"LOGIN_USER_CODE", str); } //ec_add_xml_node_value(root,"LOGIN_USER_CODE", "A5"); string cardno_begin; //开始卡号 string cardno_end; //结束卡号 int cardcnt; //卡数量 string product_group_code; //产品组代码 string product_code; //产品代码 int in_fee_amt; //内收手续费 int out_fee_amt; //外收手续费 int receivable_amt; //应收金额 int is_guarantee_deposit; //是否收取押金 int guarantee_deposit; //押金 int is_get_fee; //是否收费 int fee_amt; //发卡费 string idcode; //持卡人证件号码 string idtype; //持卡人证件类型 string name; //持卡人名 string familyname; //持卡人姓 string name_spell; //持卡人名-拼音 string familyname_spell; //持卡人姓-拼音 string birthday; //持卡人生日 string telphone; //持卡人电话号码 string mobile; //持卡人手机 string address; //持卡人地址 string postcode; //持卡人邮编 string email; //持卡人电邮 string corpname; //持卡人单位名称 string comments; //持卡人备注 string reserved; //保留 //卡片数量 { stringstream ss; COL2VAR(cardcnt); ss << cardcnt; ec_add_xml_node_value(root,"CARDCOUNT",ss.str()); } //起始卡号 { stringstream ss; COL2VAR(cardno_begin); ss <<cardno_begin; ec_add_xml_node_value(root,"STARTCARD",ss.str()); } //结束卡号 { stringstream ss; COL2VAR(cardno_end); ss <<cardno_end; ec_add_xml_node_value(root,"ENDCARD",ss.str()); } //产品组 { stringstream ss; COL2VAR(product_group_code); ss <<product_group_code; ec_add_xml_node_value(root,"PRD_GRP_CODE",ss.str()); } //产品 { stringstream ss; COL2VAR(product_code); ss <<product_code; ec_add_xml_node_value(root,"PRD_CODE",ss.str()); } //内收手续费 { stringstream ss; COL2VAR(in_fee_amt); ss << setiosflags(ios::right)<<setw(12) <<setfill('0') <<in_fee_amt; ec_add_xml_node_value(root,"TOTAL_IN_FEE_AMT",ss.str()); } //外收手续费 { stringstream ss; COL2VAR(out_fee_amt); ss << setiosflags(ios::right)<<setw(12) <<setfill('0') <<out_fee_amt; ec_add_xml_node_value(root,"TOTAL_OUT_FEE_AMT",ss.str()); } //应收金额 { stringstream ss; COL2VAR(receivable_amt); ss << setiosflags(ios::right)<<setw(12) <<setfill('0') <<receivable_amt; ec_add_xml_node_value(root,"BALAMT",ss.str()); } //是否收取押金 { stringstream ss; COL2VAR(is_guarantee_deposit); ss <<is_guarantee_deposit; ec_add_xml_node_value(root,"PLEDGEFLG",ss.str()); } //押金 { stringstream ss; COL2VAR(guarantee_deposit); ss << setiosflags(ios::right)<<setw(12) <<setfill('0') <<guarantee_deposit; ec_add_xml_node_value(root,"PLEDGE",ss.str()); } //是否收费 { stringstream ss; COL2VAR(is_get_fee); ss <<is_get_fee; ec_add_xml_node_value(root,"FEEFLG",ss.str()); } //发卡费 { stringstream ss; COL2VAR(fee_amt); ss << setiosflags(ios::right)<<setw(12) <<setfill('0') <<fee_amt; ec_add_xml_node_value(root,"FEE",ss.str()); } //持卡人证件号码 { stringstream ss; COL2VAR(idcode); ss <<idcode; ec_add_xml_node_value(root,"IDCODE",ss.str()); } //持卡人证件类型 { stringstream ss; COL2VAR(idtype); ss <<idtype; ec_add_xml_node_value(root,"IDTYPE",ss.str()); } //持卡人名 { stringstream ss; COL2VAR(name); ss <<name; ec_add_xml_node_value(root,"NAME",ss.str()); } //持卡人姓 { stringstream ss; COL2VAR(familyname); ss <<familyname; ec_add_xml_node_value(root,"SURNAME",ss.str()); } //持卡人拼音名 { stringstream ss; COL2VAR(name_spell); ss <<name_spell; ec_add_xml_node_value(root,"SPELL_NAME",ss.str()); } //持卡人拼音姓 { stringstream ss; COL2VAR(familyname_spell); ss <<familyname_spell; ec_add_xml_node_value(root,"SPELL_SURNAME",ss.str()); } //持卡人生日 { stringstream ss; COL2VAR(birthday); ss <<birthday; ec_add_xml_node_value(root,"BIRTHDAY",ss.str()); } //持卡人电话号码 { stringstream ss; COL2VAR(telphone); ss<<telphone; ec_add_xml_node_value(root,"COPHONE",ss.str()); } //持卡人手机 { stringstream ss; COL2VAR(mobile); ss<<mobile; ec_add_xml_node_value(root,"MOBILE",ss.str()); } //持卡人地址 { stringstream ss; COL2VAR(address); ss<<address; ec_add_xml_node_value(root,"ADDR",ss.str()); } //持卡人邮编 { stringstream ss; COL2VAR(postcode); ss<<postcode; ec_add_xml_node_value(root,"POST",ss.str()); } //持卡人电邮 { stringstream ss; COL2VAR(email); ss<<email; ec_add_xml_node_value(root,"EMAIL",ss.str()); } //持卡人单位名称 { stringstream ss; COL2VAR(corpname); ss<<corpname; ec_add_xml_node_value(root,"COMNAME",ss.str()); } //持卡人备注 { stringstream ss; COL2VAR(comments); ss<<comments; ec_add_xml_node_value(root,"CUSTRES",ss.str()); } //保留域 { stringstream ss; COL2VAR(reserved); ss<<reserved; ec_add_xml_node_value(root,"RESERVED",ss.str()); } //报文鉴别码 // ec_add_xml_node_value(root, "MESG_AUTHN_CODE", "87AE"); ec_bank_any_ytc::calc_trans_mac(&root); TiXmlPrinter printer; doc.Accept(&printer); char xml_header[100]="<?xml version='1.0' encoding='GBK'?>\n"; body.append(xml_header); body += printer.CStr(); return 0; }
string Edge305Device::getDeviceDescription() const { if (Log::enabledDbg()) Log::dbg("GpsDevice::getDeviceDescription() "+this->displayName); /* <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <Device xmlns="http://www.garmin.com/xmlschemas/GarminDevice/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd"> <Model> <PartNumber>006-B0450-00</PartNumber> <SoftwareVersion>320</SoftwareVersion> <Description>EDGE305 Software Version 3.20</Description> </Model> <Id>3305091776</Id> <DisplayName>Your name</DisplayName> <MassStorageMode> <DataType> <Name>GPSData</Name> <File> <Specification> <Identifier>http://www.topografix.com/GPX/1/1</Identifier> <Documentation>http://www.topografix.com/GPX/1/1/gpx.xsd</Documentation> </Specification> <Location> <FileExtension>GPX</FileExtension> </Location> <TransferDirection>InputOutput</TransferDirection> </File> </DataType> <DataType> <Name>FitnessHistory</Name> <File> <Specification> <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier> <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation> </Specification> <Location> <FileExtension>TCX</FileExtension> </Location> <TransferDirection>OutputFromUnit</TransferDirection> </File> </DataType> <DataType> <Name>FitnessUserProfile</Name> <File> <Specification> <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier> <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation> </Specification> <Location> <BaseName>UserProfile</BaseName> <FileExtension>TCX</FileExtension> </Location> <TransferDirection>InputOutput</TransferDirection> </File> </DataType> <DataType> <Name>FitnessCourses</Name> <File> <Specification> <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier> <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation> </Specification> <Location> <FileExtension>TCX</FileExtension> </Location> <TransferDirection>InputOutput</TransferDirection> </File> </DataType> <DataType> <Name>FitnessWorkouts</Name> <File> <Specification> <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier> <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation> </Specification> <Location> <FileExtension>TCX</FileExtension> </Location> <TransferDirection>InputOutput</TransferDirection> </File> </DataType> <UpdateFile> <PartNumber>006-B0450-00</PartNumber> <Version> <Major>0</Major> <Minor>0</Minor> </Version> <Description>Missing</Description> </UpdateFile> <UpdateFile> <PartNumber>006-B0478-00</PartNumber> <Version> <Major>0</Major> <Minor>0</Minor> </Version> <Description>Missing</Description> </UpdateFile> </MassStorageMode> <GarminMode> <Protocols> <Application Id="918"> <DataType>918</DataType> </Application> </Protocols> <Extensions> <GarminModeExtension xmlns="http://www.garmin.com/xmlschemas/GarminDeviceExtensions/v3"> <MemoryRegion> <Id>5</Id> <Version> <Major>0</Major> <Minor>0</Minor> </Version> <Description>Missing</Description> <ExpectedPartNumber>006-B0450-00</ExpectedPartNumber> <CurrentPartNumber>006-B0450-00</CurrentPartNumber> <IsErased>true</IsErased> <IsUserUpdateable>true</IsUserUpdateable> </MemoryRegion> <MemoryRegion> <Id>14</Id> <Version> <Major>3</Major> <Minor>20</Minor> </Version> <Description>EDGE305</Description> <ExpectedPartNumber>006-B0450-00</ExpectedPartNumber> <CurrentPartNumber>006-B0450-00</CurrentPartNumber> <IsUserUpdateable>true</IsUserUpdateable> </MemoryRegion> <MemoryRegion> <Id>246</Id> <Version> <Major>0</Major> <Minor>0</Minor> </Version> <Description>Missing</Description> <ExpectedPartNumber>006-B0478-00</ExpectedPartNumber> <CurrentPartNumber>006-B0478-00</CurrentPartNumber> <IsErased>true</IsErased> <IsUserUpdateable>true</IsUserUpdateable> </MemoryRegion> </GarminModeExtension> </Extensions> </GarminMode> </Device> */ garmin_unit garmin; if ( garmin_init(&garmin,0) != 0 ) { garmin_close(&garmin); } else { Log::err("Opening of garmin device failed. No longer attached!?"); return ""; } TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "no" ); doc.LinkEndChild( decl ); /*<Device xmlns="http://www.garmin.com/xmlschemas/GarminDevice/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd">*/ TiXmlElement * device = new TiXmlElement( "Device" ); device->SetAttribute("xmlns", "http://www.garmin.com/xmlschemas/GarminDevice/v2"); device->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); device->SetAttribute("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd"); doc.LinkEndChild( device ); /*<Model> <PartNumber>006-B0450-00</PartNumber> <SoftwareVersion>320</SoftwareVersion> <Description>EDGE305 Software Version 3.20</Description> </Model> */ TiXmlElement * model = new TiXmlElement( "Model" ); TiXmlElement * partnumber = new TiXmlElement( "PartNumber" ); partnumber->LinkEndChild(new TiXmlText("006-B0450-00")); TiXmlElement * version = new TiXmlElement( "SoftwareVersion" ); std::stringstream ss; ss << garmin.product.software_version; version->LinkEndChild(new TiXmlText( ss.str() )); TiXmlElement * descr = new TiXmlElement( "Description" ); descr->LinkEndChild(new TiXmlText(this->displayName)); model->LinkEndChild(partnumber); model->LinkEndChild(version); model->LinkEndChild(descr); device->LinkEndChild( model ); /* <Id>3333333333</Id> */ TiXmlElement * id = new TiXmlElement( "Id" ); ss.str(""); // empty stringstream ss << garmin.id; id->LinkEndChild(new TiXmlText(ss.str())); device->LinkEndChild(id); /* <DisplayName>Your name</DisplayName>*/ TiXmlElement * dispName = new TiXmlElement( "DisplayName" ); dispName->LinkEndChild(new TiXmlText(this->displayName)); device->LinkEndChild(dispName); TiXmlElement * massStorage = new TiXmlElement( "MassStorageMode" ); device->LinkEndChild(massStorage); /* <DataType> <Name>GPSData</Name> <File> <Specification> <Identifier>http://www.topografix.com/GPX/1/1</Identifier> <Documentation>http://www.topografix.com/GPX/1/1/gpx.xsd</Documentation> </Specification> <Location> <FileExtension>GPX</FileExtension> </Location> <TransferDirection>InputOutput</TransferDirection> </File> </DataType> */ TiXmlElement * dataTypes = new TiXmlElement( "DataType" ); massStorage->LinkEndChild(dataTypes); TiXmlElement * name = new TiXmlElement( "Name" ); name->LinkEndChild(new TiXmlText("GPSData")); dataTypes->LinkEndChild(name); TiXmlElement * file = new TiXmlElement( "File" ); dataTypes->LinkEndChild(file); TiXmlElement * spec = new TiXmlElement( "Specification" ); file->LinkEndChild(spec); TiXmlElement * identifier = new TiXmlElement( "Identifier" ); identifier->LinkEndChild(new TiXmlText("http://www.topografix.com/GPX/1/1")); spec->LinkEndChild(identifier); TiXmlElement * docu = new TiXmlElement( "Documentation" ); docu->LinkEndChild(new TiXmlText("http://www.topografix.com/GPX/1/1/gpx.xsd")); spec->LinkEndChild(docu); TiXmlElement * loc = new TiXmlElement( "Location" ); file->LinkEndChild(loc); TiXmlElement * fileEx = new TiXmlElement( "FileExtension" ); fileEx->LinkEndChild(new TiXmlText("GPX")); loc->LinkEndChild(fileEx); TiXmlElement * transferDir = new TiXmlElement( "TransferDirection" ); transferDir->LinkEndChild(new TiXmlText("InputOutput")); file->LinkEndChild(transferDir); /* <DataType> <Name>FitnessHistory</Name> <File> <Specification> <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier> <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation> </Specification> <Location> <FileExtension>TCX</FileExtension> </Location> <TransferDirection>OutputFromUnit</TransferDirection> </File> </DataType> */ dataTypes = new TiXmlElement( "DataType" ); massStorage->LinkEndChild(dataTypes); name = new TiXmlElement( "Name" ); name->LinkEndChild(new TiXmlText("FitnessHistory")); dataTypes->LinkEndChild(name); file = new TiXmlElement( "File" ); dataTypes->LinkEndChild(file); spec = new TiXmlElement( "Specification" ); file->LinkEndChild(spec); identifier = new TiXmlElement( "Identifier" ); identifier->LinkEndChild(new TiXmlText("http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2")); spec->LinkEndChild(identifier); docu = new TiXmlElement( "Documentation" ); docu->LinkEndChild(new TiXmlText("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd")); spec->LinkEndChild(docu); loc = new TiXmlElement( "Location" ); file->LinkEndChild(loc); fileEx = new TiXmlElement( "FileExtension" ); fileEx->LinkEndChild(new TiXmlText("TCX")); loc->LinkEndChild(fileEx); transferDir = new TiXmlElement( "TransferDirection" ); transferDir->LinkEndChild(new TiXmlText("InputOutput")); file->LinkEndChild(transferDir); TiXmlPrinter printer; printer.SetIndent( "\t" ); doc.Accept( &printer ); string str = printer.Str(); if (Log::enabledDbg()) Log::dbg("GpsDevice::getDeviceDescription() Done: "+this->displayName ); return str; }
int TextHandler::build_word_result_file(const TextID & tid, const string & build_id, const string & file_type, const string & result_text, string & result_file_name) { string word_uuid = tid + "-" + build_id; //生成xml stringstream ss; ss << result_text; string xmldata; TiXmlDocument * xmlDocs = new TiXmlDocument(); try { TiXmlDeclaration *pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", ""); xmlDocs->LinkEndChild(pDeclaration); TiXmlElement * docElem = new TiXmlElement("document"); xmlDocs->LinkEndChild(docElem); string line; size_t i=1; while(getline(ss, line)) { TiXmlElement * pElem = new TiXmlElement("p"); docElem->LinkEndChild(pElem); pElem->SetAttribute("index", i); TiXmlText * contentText = new TiXmlText(line); pElem->LinkEndChild(contentText); ++i; } docElem->SetAttribute("id", word_uuid); //输出到xmldata TiXmlPrinter print; xmlDocs->Accept(&print); xmldata = print.CStr(); }catch(...) { return ERR_CREATE_WORD_RESULT_XML; } //输出到word解析工作目录下进行还原 string cmd; #ifdef WINDOWS cmd = "copy \"" + m_word_workspace + "/" + tid + ".word.tmp\" \"" + m_word_workspace + "/" + word_uuid + ".word.tmp\""; #else cmd = "cp \"" + m_word_workspace + "/" + tid + ".word.tmp\" \"" + m_word_workspace + "/" + word_uuid + ".word.tmp\""; #endif //lout << cmd << endl; system(cmd.c_str()); string xml_data_path = m_word_workspace + "/" + word_uuid + ".word.xml"; if(false == write_file(xml_data_path, xmldata.c_str(), xmldata.size())) { return ERR_SAVE_WORD_RECOVER_XML; } result_file_name = tid + "." + build_id + ".result." + file_type; string result_path = this->m_default_file_path + result_file_name; cmd = "java -jar ./mdata/word/WordDocumentExtractor.jar generate -t \"" + file_type + "\" -o \"" + result_path + "\" -m \"" + m_word_workspace + "/" + word_uuid + ".word.tmp\" -x \"" + m_word_workspace + "/" + word_uuid + ".word.xml\""; //lout << "Word generate cmd: " << cmd << endl; system(cmd.c_str()); return SUCCESS; }
HRESULT CSafeSaverNetImpl::CopyCfData(SCfData& sCfData) { CCameraData* pCameraData = sCfData.pRefData->GetItem(); DWORD32 dwDataLen = 0; memcpy((char*)m_sBuf.addr + dwDataLen, &pCameraData->header, sizeof(pCameraData->header)); dwDataLen += sizeof(pCameraData->header); memcpy((char*)m_sBuf.addr + dwDataLen, pCameraData->pbInfo, pCameraData->header.dwInfoSize); dwDataLen += pCameraData->header.dwInfoSize; memcpy((char*)m_sBuf.addr + dwDataLen, pCameraData->pbData, pCameraData->header.dwDataSize); dwDataLen += pCameraData->header.dwDataSize; if (0 == sCfData.iDataType)//识别结果,修正CarID { BLOCK_HEADER cBlockHeader; char* pXML = NULL; char* pbTemp = (char*)m_sBuf.addr + sizeof(CAMERA_INFO_HEADER); //修正数据类型 DWORD32 dwRecordType = CAMERA_RECORD_HISTORY; memcpy(pbTemp+8, &dwRecordType, 4); for (int i = 0; i < (int)pCameraData->header.dwInfoSize; ) { memcpy(&cBlockHeader, pbTemp, sizeof(BLOCK_HEADER)); pbTemp += sizeof(BLOCK_HEADER); i += sizeof(BLOCK_HEADER); if (cBlockHeader.dwID == BLOCK_XML_TYPE) // 识别结果XML附加信息 { pXML = pbTemp; if (strstr(pXML, "违章:是")) { sCfData.dwDataInfo = 1; } break; } pbTemp += cBlockHeader.dwLen; i += cBlockHeader.dwLen; } TiXmlDocument xmlDoc; xmlDoc.Parse(pXML); if (pXML && xmlDoc.RootElement()) { TiXmlElement* pElement = xmlDoc.RootElement()->FirstChildElement("ResultSet"); if (pElement) { pElement = pElement->FirstChildElement("Result"); } TiXmlElement* pElementCarId = NULL; TiXmlElement* pElementTimeLow = NULL; TiXmlElement* pElementTimeHigh = NULL; if (pElement) { pElementCarId = pElement->FirstChildElement("CarID"); pElementTimeLow = pElement->FirstChildElement("TimeLow"); pElementTimeHigh = pElement->FirstChildElement("TimeHigh"); } if (pElementTimeLow) { const TiXmlAttribute* attr = pElementTimeLow->FirstAttribute(); for (; attr; attr=attr->Next()) { if (0 == strcmp(attr->Name(), "value")) { sscanf(attr->Value(), "%u", &sCfData.dwTimeLow); break; } } } if (pElementTimeHigh) { const TiXmlAttribute* attr = pElementTimeHigh->FirstAttribute(); for (; attr; attr=attr->Next()) { if (0 == strcmp(attr->Name(), "value")) { sscanf(attr->Value(), "%u", &sCfData.dwTimeHigh); break; } } } if (pElementCarId) { #if FIX_FILE_VER == 1 DWORD32 dwCarID = m_cCfRecord.GetHourCount(sCfData.dwTimeLow, sCfData.dwTimeHigh); #else DWORD32 dwCarID; GetHourCount(sCfData.dwTimeLow, sCfData.dwTimeHigh, &dwCarID); sCfData.dwIndex = dwCarID; #endif char szValue[32] = {0}; sprintf(szValue, "%u", dwCarID); pElementCarId->SetAttribute("value", szValue); TiXmlPrinter cTxPr; xmlDoc.Accept(&cTxPr); strcpy(pXML, cTxPr.CStr()); } } } else { REAL_TIME_STRUCT rtsTime; ConvertMsToTime(sCfData.dwTimeLow, sCfData.dwTimeHigh, &rtsTime); sCfData.dwIndex = rtsTime.wMinute * 60 + rtsTime.wSecond; } return S_OK; }
// on_create_result_1 int TextHandler::build_tmx_result_file(const TextID & tid, string & result_file_name) { int ret = SUCCESS; //从数据库读取翻译结果 vector<boost::tuple<string, string, string> > result_vec; string tgt_language; ret = DBOperation::GetTransResultPair(tid, result_vec, tgt_language); if(SUCCESS != ret) { return ERR_GET_TGT_VEC_FROM_DB; } //生成TMX 格式数据 string tmx_data; //<?xml version="1.0" encoding=UTF-8" ?> // //<tmx version="1.4"> // <header creationdate="" <!--创建日期--> // creationtool="" <!--创建工具--> // creationtoolversion="" <!--创建工具的版本--> // datatype="unknown" <!--数据类型:有很多种,一般使用默认--> // o-tmf="unknown" <!--源存储格式--> // segtype="block" <!--段值:block,paragraph,sentence,phrase--> // srclang="*all*" <!--源语言:常使用*all*--> // adminlang="en"/> <!--Administrative language--> // // <body> // <tu changedate=""> <!--修改日期--> // <tuv xml:lang="en"><seg>introduction</seg></tuv> // <tuv xml:lang="zh-cn"><seg>简介</seg></tuv> // </tu> // <tu changedate=""> // <tuv xml:lang="en"><seg>conclusion</seg></tuv> // <tuv xml:lang="zh-cn"><seg>总结</seg></tuv> // </tu> // </body> //</tmx> TiXmlDocument * xmlDocs = new TiXmlDocument(); try { //声明 TiXmlDeclaration* dec = new TiXmlDeclaration("1.0", "UTF-8", ""); xmlDocs->LinkEndChild(dec); //tmx 节点 TiXmlElement * tmxElem = new TiXmlElement("tmx"); xmlDocs->LinkEndChild(tmxElem); //header节点 TiXmlElement * headerElem = new TiXmlElement("header"); headerElem->SetAttribute("creationdate", ""); headerElem->SetAttribute("creationtool", "ict_trans"); headerElem->SetAttribute("creationtoolversion", "1.0"); headerElem->SetAttribute("datatype", "unknown"); headerElem->SetAttribute("o-tmf", "unknown"); headerElem->SetAttribute("segtype", "sentence"); headerElem->SetAttribute("srclang", "en"); headerElem->SetAttribute("srclang", "zh-cn"); tmxElem->LinkEndChild(headerElem); //body节点 TiXmlElement * bodyElem = new TiXmlElement("body"); tmxElem->LinkEndChild(bodyElem); //loop tu 节点 for(size_t i=0; i<result_vec.size(); ++i) { //tu节点 TiXmlElement * tuElem = new TiXmlElement("tu"); bodyElem->LinkEndChild(tuElem); //tuv 节点对 string * p_english = NULL; string * p_chinese = NULL; if(LANGUAGE_CHINESE == tgt_language) { p_english = &result_vec[i].get<0>(); if(result_vec[i].get<2>().size() > 0) { CLanguage::En2ChPost(result_vec[i].get<2>()); p_chinese = &result_vec[i].get<2>(); }else { p_chinese = &result_vec[i].get<1>(); } }else { p_chinese = &result_vec[i].get<0>(); if(result_vec[i].get<2>().size() > 0) { CLanguage::Ch2EnPost(result_vec[i].get<2>()); p_english = &result_vec[i].get<2>(); }else { p_english = &result_vec[i].get<1>(); } } //tuv-en TiXmlElement * tuvenElem = new TiXmlElement("tuv"); TiXmlText * tuvenText = new TiXmlText(p_english->c_str()); tuvenElem->SetAttribute("xml:lang", "en"); tuvenElem->LinkEndChild(tuvenText); tuElem->LinkEndChild(tuvenElem); //tuv-ch TiXmlElement * tuvchElem = new TiXmlElement("tuv"); TiXmlText * tuvchText = new TiXmlText(p_chinese->c_str()); tuvenElem->SetAttribute("xml:lang", "zh-ch"); tuvchElem->LinkEndChild(tuvchText); tuElem->LinkEndChild(tuvchElem); } //输出到xmldata TiXmlPrinter print; xmlDocs->Accept(&print); tmx_data = print.CStr(); }catch (...) { lerr << "Create xml-tmx failed." << endl; delete xmlDocs; return ERR_USR_XML_PARSER; } delete xmlDocs; //写入到文件 string build_id = GenerateUUID(); result_file_name = tid + "." + build_id + ".tmx"; string tmx_filepath = m_default_file_path + result_file_name; if(false == write_file(tmx_filepath, tmx_data.c_str(), tmx_data.size())) { return ERR_OPEN_RESULT_FILE_FAILED; } return SUCCESS; }
int ServiceLogicFacade::Trace(struct soap* soap, _ns2__Trace* request, _ns2__TraceResponse* response) const { RasterImage* rasterImage = NULL; VectorImage* vectorImage = NULL; TiXmlDocument* svgXmlDocument = NULL; try { if (!securityModule->CheckSystemID(request->authToken)) { response->statusCode = StatusCodes::FORBIDDEN; logger->LogMessage("Authentication token {" + request->authToken + "} is invalid. Access denied."); return SOAP_OK; } //decode image data from base64 string decodedImgData; bool encodingSuccessful = Base64::Decode(request->imageData, decodedImgData); if (!encodingSuccessful) { response->statusCode = StatusCodes::DECODING_ERROR; goto CLEANUP; } istringstream sourceImageStream(decodedImgData); //create RasterImage instance try { rasterImage = WinBMP::FromStream(sourceImageStream); } catch (const ImTrcr::Imaging::InvalidBmpStreamException& ex) { response->statusCode = StatusCodes::WRONG_FORMAT_ERROR; logger->LogMessage("Wrong format of received image. Vectorization failed. Authentication token of external system is {" + request->authToken + "}."); goto CLEANUP; } catch (...) { response->statusCode = StatusCodes::WRONG_FORMAT_ERROR; logger->LogMessage("Wrong format of received image. Vectorization failed. Authentication token of external system is {" + request->authToken + "}."); goto CLEANUP; } TracingOptions opts; if (!StringUtils::TryParseInt(request->despecklingPixels, opts.despecklingPixels)) { response->statusCode = StatusCodes::WRONG_FORMAT_ERROR; goto CLEANUP; } if (!StringUtils::TryParseInt(request->angularity, opts.angularity)) { response->statusCode = StatusCodes::WRONG_FORMAT_ERROR; goto CLEANUP; } //trace RasterImage instance to VectorImage instance try { vectorImage = tracer->Trace(*rasterImage, opts); } catch (...) { response->statusCode = StatusCodes::TRACING_ERROR; goto CLEANUP; } //serialize VectorImage to SVG XML and put it into response object svgXmlDocument = svgSerializer->Serialize(*vectorImage); TiXmlPrinter printer; printer.SetStreamPrinting(); svgXmlDocument->Accept(&printer); response->svgXml = printer.CStr(); response->statusCode = StatusCodes::OK; goto CLEANUP; } catch (...) { response->statusCode = StatusCodes::UNKNOWN_ERROR; goto CLEANUP; } CLEANUP: MemoryUtils::SafeFree(&rasterImage); MemoryUtils::SafeFree(&vectorImage); MemoryUtils::SafeFree(&svgXmlDocument); return SOAP_OK; }
string MessageBox::getXml() { /* <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <MessageBox xmlns="http://www.garmin.com/xmlschemas/PluginAPI/v1" DefaultButtonValue="2"> <Icon>Question</Icon> <Text>The file F:/Garmin/gpx/GC22K31.gpx already exists on your GPS Device. OK to overwrite the file?</Text> <Button Caption="OK" Value="1"/> <Button Caption="Cancel" Value="2"/> </MessageBox> */ TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "no" ); doc.LinkEndChild( decl ); TiXmlElement * msgBox = new TiXmlElement( "MessageBox" ); msgBox->SetAttribute("xmlns", "http://www.garmin.com/xmlschemas/PluginAPI/v1"); msgBox->SetAttribute("DefaultButtonValue", this->defaultButton); doc.LinkEndChild( msgBox ); TiXmlElement * icon = new TiXmlElement( "Icon" ); if (this->type == Question) { icon->LinkEndChild(new TiXmlText("Question")); } else { Log::err("MessageBox::getXml Message type not yet implemented!"); icon->LinkEndChild(new TiXmlText("Unknown")); } msgBox->LinkEndChild( icon ); TiXmlElement * textelem = new TiXmlElement( "Text" ); textelem->LinkEndChild(new TiXmlText(this->text)); msgBox->LinkEndChild( textelem ); if ((this->buttons & BUTTON_OK) > 0) { TiXmlElement * btn = new TiXmlElement( "Button" ); btn->SetAttribute("Caption", "OK"); btn->SetAttribute("Value", BUTTON_OK); msgBox->LinkEndChild( btn ); } if ((this->buttons & BUTTON_CANCEL) > 0) { TiXmlElement * btn = new TiXmlElement( "Button" ); btn->SetAttribute("Caption", "Cancel"); btn->SetAttribute("Value", BUTTON_CANCEL); msgBox->LinkEndChild( btn ); } if ((this->buttons & BUTTON_YES) > 0) { TiXmlElement * btn = new TiXmlElement( "Button" ); btn->SetAttribute("Caption", "Yes"); btn->SetAttribute("Value", BUTTON_YES); msgBox->LinkEndChild( btn ); } if ((this->buttons & BUTTON_NO) > 0) { TiXmlElement * btn = new TiXmlElement( "Button" ); btn->SetAttribute("Caption", "No"); btn->SetAttribute("Value", BUTTON_NO); msgBox->LinkEndChild( btn ); } TiXmlPrinter printer; //printer.SetIndent( "\t" ); doc.Accept( &printer ); string str = printer.Str(); return str; }
//DecodeXml int CParseDevice::DecodeXml(const char *xml, int sock_fd) { if (NULL == xml) { printf("ERROR:Empty xml message...\n"); return -1; } TiXmlDocument *handle = new TiXmlDocument(); TiXmlPrinter *printer = new TiXmlPrinter(); handle->Parse(xml); TiXmlNode* EnvelopeNode = handle->FirstChild("Envelope"); const char * EnvelopeType = EnvelopeNode->ToElement()->Attribute("type"); if(EnvelopeType != NULL){ if(!strcmp(EnvelopeType,"r_pregister")){ cms_fd = sock_fd; return 0; } if (cms_fd == sock_fd){ if(!strcmp(EnvelopeType,"getrtspuri")){ EnvelopeNode->ToElement()->SetAttribute("type","r_getrtspuri"); TiXmlNode* profileNode = EnvelopeNode->FirstChildElement("profile"); int count = 0; while(profileNode){ DeviceInfo devInfo; memset(&devInfo, 0, sizeof(devInfo)); const char* szXmlValue = NULL; TiXmlNode* profile = profileNode->FirstChildElement("deviceip"); if(profile != NULL){ szXmlValue = profile->ToElement()->GetText(); devInfo.m_nId = rtspcount++; int a[4]; sscanf(szXmlValue, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]); char ipbuffer[32]; sprintf(ipbuffer, "%xx%xx%xx%x%c",a[0], a[1], a[2], a[3], (char)(count +103 )); strncpy(devInfo.m_szIdname, ipbuffer, strlen(ipbuffer)); } profile = profileNode->FirstChildElement("token"); if(profile != NULL){ szXmlValue = profile->ToElement()->GetText(); } profile = profileNode->FirstChildElement("sourceuri"); if(profile != NULL){ szXmlValue = profile->ToElement()->GetText(); if(szXmlValue != NULL) strncpy(devInfo.m_szSourceUrl, szXmlValue, sizeof(devInfo.m_szSourceUrl)); } //Add Device if(strcmp(devInfo.m_szSourceUrl,"") != 0){ if (success != AddDevice(devInfo)){ printf("ERROR:Add new ProxySession:%s Falied!",devInfo.m_szSourceUrl); TiXmlText *DestContent = new TiXmlText("None"); TiXmlElement *DestElement = new TiXmlElement("desturi"); DestElement->LinkEndChild(DestContent); profileNode->ToElement()->LinkEndChild(DestElement); }else{ char desturl[500]; memset(desturl,0,strlen(desturl)); sprintf(desturl, "rtsp://%s:8554/%s", server_addr, devInfo.m_szIdname); printf("INFO:Add new ProxySession:%s\nProxy this Session from %s\n",devInfo.m_szSourceUrl,desturl); TiXmlText *DestContent = new TiXmlText(desturl); TiXmlElement *DestElement = new TiXmlElement("desturi"); DestElement->LinkEndChild(DestContent); profileNode->ToElement()->LinkEndChild(DestElement); } } profileNode = profileNode->NextSiblingElement("profile"); count++; } handle->Accept( printer ); if (send ( sock_fd, printer->CStr() , strlen(const_cast<char *>(printer->CStr())), 0) == - 1) { perror ( "ERROR:Send error\n" ); return -1; } delete handle; delete printer; return 0; } } } return -1; }
void mitk::PlanarFigureWriter::GenerateData() { m_Success = false; if (!m_WriteToMemory && m_FileName.empty()) { MITK_ERROR << "Could not write planar figures. File name is invalid"; throw std::invalid_argument("file name is empty"); } TiXmlDocument document; auto decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... document.LinkEndChild( decl ); auto version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__ ); version->SetAttribute("CVSRevision", "$Revision: 17055 $" ); version->SetAttribute("FileVersion", 1 ); document.LinkEndChild(version); /* create xml element for each input */ for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i ) { // Create root element for this PlanarFigure InputType::Pointer pf = this->GetInput( i ); if (pf.IsNull()) continue; auto pfElement = new TiXmlElement("PlanarFigure"); pfElement->SetAttribute("type", pf->GetNameOfClass()); document.LinkEndChild(pfElement); if ( pf->GetNumberOfControlPoints() == 0 ) continue; //PlanarFigure::VertexContainerType* vertices = pf->GetControlPoints(); //if (vertices == NULL) // continue; // Serialize property list of PlanarFigure mitk::PropertyList::Pointer propertyList = pf->GetPropertyList(); mitk::PropertyList::PropertyMap::const_iterator it; for ( it = propertyList->GetMap()->begin(); it != propertyList->GetMap()->end(); ++it ) { // Create seralizer for this property const mitk::BaseProperty* prop = it->second; std::string serializerName = std::string( prop->GetNameOfClass() ) + "Serializer"; std::list< itk::LightObject::Pointer > allSerializers = itk::ObjectFactoryBase::CreateAllInstance( serializerName.c_str() ); if ( allSerializers.size() != 1 ) { // No or too many serializer(s) found, skip this property continue; } mitk::BasePropertySerializer* serializer = dynamic_cast< mitk::BasePropertySerializer* >( allSerializers.begin()->GetPointer() ); if ( serializer == nullptr ) { // Serializer not valid; skip this property } auto keyElement = new TiXmlElement( "property" ); keyElement->SetAttribute( "key", it->first ); keyElement->SetAttribute( "type", prop->GetNameOfClass() ); serializer->SetProperty( prop ); TiXmlElement* valueElement = nullptr; try { valueElement = serializer->Serialize(); } catch (...) { } if ( valueElement == nullptr ) { // Serialization failed; skip this property continue; } // Add value to property element keyElement->LinkEndChild( valueElement ); // Append serialized property to property list pfElement->LinkEndChild( keyElement ); } // Serialize control points of PlanarFigure auto controlPointsElement = new TiXmlElement("ControlPoints"); pfElement->LinkEndChild(controlPointsElement); for (unsigned int i = 0; i < pf->GetNumberOfControlPoints(); i++) { auto vElement = new TiXmlElement("Vertex"); vElement->SetAttribute("id", i); vElement->SetDoubleAttribute("x", pf->GetControlPoint(i)[0]); vElement->SetDoubleAttribute("y", pf->GetControlPoint(i)[1]); controlPointsElement->LinkEndChild(vElement); } auto geoElement = new TiXmlElement("Geometry"); const PlaneGeometry* planeGeo = dynamic_cast<const PlaneGeometry*>(pf->GetPlaneGeometry()); if (planeGeo != nullptr) { // Write parameters of IndexToWorldTransform of the PlaneGeometry typedef mitk::Geometry3D::TransformType TransformType; const TransformType* affineGeometry = planeGeo->GetIndexToWorldTransform(); const TransformType::ParametersType& parameters = affineGeometry->GetParameters(); auto vElement = new TiXmlElement( "transformParam" ); for ( unsigned int i = 0; i < affineGeometry->GetNumberOfParameters(); ++i ) { std::stringstream paramName; paramName << "param" << i; vElement->SetDoubleAttribute( paramName.str().c_str(), parameters.GetElement( i ) ); } geoElement->LinkEndChild( vElement ); // Write bounds of the PlaneGeometry typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType; const BoundsArrayType& bounds = planeGeo->GetBounds(); vElement = new TiXmlElement( "boundsParam" ); for ( unsigned int i = 0; i < 6; ++i ) { std::stringstream boundName; boundName << "bound" << i; vElement->SetDoubleAttribute( boundName.str().c_str(), bounds.GetElement( i ) ); } geoElement->LinkEndChild( vElement ); // Write spacing and origin of the PlaneGeometry Vector3D spacing = planeGeo->GetSpacing(); Point3D origin = planeGeo->GetOrigin(); geoElement->LinkEndChild(this->CreateXMLVectorElement("Spacing", spacing)); geoElement->LinkEndChild(this->CreateXMLVectorElement("Origin", origin)); pfElement->LinkEndChild(geoElement); } } if(m_WriteToMemory) { // Declare a printer TiXmlPrinter printer; // attach it to the document you want to convert in to a std::string document.Accept(&printer); // Create memory buffer and print tinyxmldocument there... m_MemoryBufferSize = printer.Size() + 1; m_MemoryBuffer = new char[m_MemoryBufferSize]; strcpy(m_MemoryBuffer,printer.CStr()); } else { if (document.SaveFile( m_FileName) == false) { MITK_ERROR << "Could not write planar figures to " << m_FileName << "\nTinyXML reports '" << document.ErrorDesc() << "'"; throw std::ios_base::failure("Error during writing of planar figure xml file."); } } m_Success = true; }