rcplusplus
rcplusplus

Reputation: 2877

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?

Upvotes: 4

Views: 10988

Answers (3)

NealChens
NealChens

Reputation: 21

You can use the SetText() function to add blank content so that you can achieve the desired effect

XMLNode *node = doc.NewElement("foo");
node->SetText("");
doc.InsertEndChild(node);
doc.SaveFile("demo2.xml");

Upvotes: 2

JeffChinese
JeffChinese

Reputation: 41

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");

Upvotes: 4

Bart
Bart

Reputation: 20038

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.

Upvotes: 4

Related Questions