C++ tinyxml2::NewElement()

C++ tinyxml2::NewElement()

NewElement() creates a new Element associated with the Document. The memory for the Element is managed by the Document.


XMLElement* tinyxml2::XMLDocument::NewElement(const char * name)




<book id="100" name="Tinyxml2" edition="2">



NewElement.cpp (Filename):-

/*include necessary header files*/

#include <iostream>

#include <cstdlib>

#include "tinyxml2.h"

using namespace std;

using namespace tinyxml2;

int main()


tinyxml2::XMLDocument doc;




cout << " Output : Using NewElement() function of tinyxml2 " << endl;


tinyxml2::XMLElement* rootNode = doc.FirstChildElement();


tinyxml2::XMLElement* childNode = rootNode->FirstChildElement();

tinyxml2::XMLComment* newComment = doc.NewComment("This is New Comment Inserted");

tinyxml2::XMLElement* newElement = doc.NewElement("Title");

/*This will add New Element in Your XML file.*/

newElement->SetAttribute("Id : ", "501");

/*This will set Attributes to Newly created Element in Your XML file.*/



childNode->InsertAfterChild(newComment, newElement);

cout << "\n New Element is Inserted Successfully in your XML File." << endl;


return 0;


Output :-


After this Tinyxml2 NewElement.exe program runs successfully. We can See that new Element is inserted with name Title with attribute Id. 

A file "NewElement_demo_file.xml" is updated as follows using savefile().


NewElement_demo_file.xml  (After execution of NewElement.exe file):-



<book id="100" name="Tinyxml2" edition="2">

<!--This is New Comment Inserted-->

<Title Id : ="501"/>