Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TinyXML2/C++ - Insert an element

Tags:

c++

xml

tinyxml2

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?

like image 662
rcplusplus Avatar asked Oct 26 '25 19:10

rcplusplus


2 Answers

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.

like image 188
Bart Avatar answered Oct 29 '25 07:10

Bart


between if, you may modify your code as follow:

XMLElement *node = doc.NewElement("foo");
XMLText *text = doc.NewText("Another Hello!");    
node->LinkEndChild(text);     
doc.LinkEndChild(node);

doc.SaveFile("demo2.xml");
like image 28
JeffChinese Avatar answered Oct 29 '25 07:10

JeffChinese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!