C++ tinyxml2::XMLNode::InsertAfterChild()

C++ tinyxml2::XMLNode::InsertAfterChild()

InsertAfterChild() adds a node after the specified child node. If the child node 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 afterThis node is not a child of this node, or if the node does not belong to the same document.


XMLNode* tinyxml2::XMLNode::InsertAfterChild(XMLNode * afterThis,XMLNode *addThis)





<book id="501">


<name value="Tinyxml2"/>


<edition number="2"/>




InsertAfterChild.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 InsertAfterChild() function of tinyxml2 " << endl;


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


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


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


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

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


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

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


rootNode->InsertAfterChild(childNode, newComment);


rootNode->InsertAfterChild(newComment, newElement);


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


return 0;


Output :-

After this Tinyxml2 InsertAfterChild.exe program runs successfully.  We can see that After
"Book id=501" Child Element, New Element is inserted after it with name New_Book.

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

InsertAfterChild_demo_file.xml  (After execution of InsertAfterChild.exe file)



<book id="501">


<name value="Tinyxml2"/>


<edition number="2"/>




<!--This is New Comment for Book-502 Inserted-->

<New_Book Id : ="502"/>