c++xmlinserttinyxmlsubtree

Inserting a subtree from text into an existing XML file using tinyxml2


I was not allowed to create the new tag 'tinyxml2', that's why I am using the tag 'tinyxml', however I am using 'tinyxml2' !

I am trying to insert a subtree element to an existing XML file. My problem is, that after running the program and checking the XML file the subtree simply does not exist within the document. In the original code I am also checking for errors while loading and saving the file so there is no problem with these functions, they are working correctly. I tried a few different approaches and also adding a single element by using the UserList.NewElement(*name*)-function does also work fine. Now I want to insert a whole subtree from a text variable...

My latest approach looks like this (simplified without checking LoadFile and SaveFile):

tinyxml2::XMLDocument UserList;
UserList.LoadFile(*Path*);

const char* XMLText = "<user name=\"test-user\" gender=\"male\"><ability description=\"I_can_do_magic\" /></user>";

tinyxml2::XMLDocument TestParse;
TestParse.Parse(XMLText);
tinyxml2::XMLElement* myNewUser = TestParse.RootElement();
UserList.FirstChildElement( "magicians" )->InsertEndChild(myNewUser);
UserList.SaveFile(*Path*);

By the way... When I tried to parse my XMLText by using the tinyxml2::XMLDocument UserList the saved XML file will be empty after running the program. This means neither the original XML Document content, nor the newly parsed subtree will be saved when trying to do this. This fact made me use the second tinyxml2::XMLDocument TestParse. Now the XML file is saved containing it's original content, however the parsed subtree is still missing... thank you very much for any solution / help / advice.


Solution

  • TinyXML-2 allocates memory for its nodes (XMLNode) in memory pools stored in the XMLDocument. This fixes the memory fragmentation problems present in TinyXML-1.

    The side effect is that elements can not be moved from one XMLDocument to another. They can only be copied. Regrettably, TinyXML-2 doesn't currently support deep copies (tree copies), so can't do what you want. (Although a deep copy is a requested on the github site.)

    I would expect the code you wrote to assert (in debug mode) or crash, by the way, since myNewUser is in a different memory pool from UserList.