c++xmltinyxml2

TinyXML2/C++ - Insert an element


I wanted to serialize objects with XML, so I got TinyXML. However I went with the newer TinyXML2. Problem is, I can't find a tutorial anywhere, so I just read the documentation. However, I seem to be stuck with adding an element to the document.

Could someone tell me what is wrong with my code?

Here's my demo.xml file contents:

<?xml version="1.0" ?>
<Hello>World</Hello>

here's my main() method:

#include "tinyxml2/tinyxml2.h"
using namespace tinyxml2;

int main (int argc, char * const argv[]) 
{
   XMLDocument doc;
   if (doc.LoadFile("demo.xml") == XML_SUCCESS)
   {
      XMLNode *node = doc.NewElement("foo");
      doc.InsertEndChild(node);
      doc.SaveFile("demo2.xml");
   }
}

and finally, here's the demo2.xml file:

<?xml version="1.0" ?>
<Hello>World</Hello>

<foo/>

Foo should look like this: <foo></foo>

But it doesn't for some reason. Can anyone explain why?


Solution

  • In fact, it shouldn't look like that. You don't put any data "in between" your <foo>...</foo> tags. As such <foo/> (note the slash) is a correct representation of what you have.