C++ tinyxml2::XMLNode::InsertFirstChild()














































C++ tinyxml2::XMLNode::InsertFirstChild()




InsertFirstChild() adds a child node as the first (left) child. If the child is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document.



Syntax:-


XMLNode* tinyxml2::XMLNode::InsertFirstChild(XMLNode *addThis)


Example:-


InsertFirstChild_demo_file.xml:-


<book_info>

   

<book id="100">


        <name value="Tinyxml2"/>


        <edition number="2"/>

   

</book>


</book_info>


InsertFirstChild.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("InsertFirstChild_demo_file.xml");

   

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

   

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

   

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

  

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(newElement);

  

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

   

doc.SaveFile("InsertFirstChild_demo_file.xml");


return 0;


}


Output :-

   


After this Tinyxml2 InsertFirstChild.exe program runs successfully. We can see that First
Child Element is inserted with name Title with attribute Id.

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


InsertFirstChild_demo_file.xml  (After execution of InsertFirstChild.exe file)

<book_info>

 

<book id="100">

       

<Title Id : ="501"/>

       

<name value="Tinyxml2"/>

       

<edition number="2"/>

   

</book>


</book_info>


Comments