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.


Syntax:-


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


Example:-


NewElement_demo_file.xml:-


<book_info>


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

 
</book>


</book_info>


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;

  

doc.LoadFile("NewElement_demo_file.xml");

  

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->InsertFirstChild(newComment);


childNode->InsertAfterChild(newComment, newElement);


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


doc.SaveFile("NewElement_demo_file.xml");


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_info>

   

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


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


<Title Id : ="501"/>


</book>


</book_info>


Comments