XMLDocument xmlDoc;
XMLNode * pRoot = xmlDoc.NewElement("Head");
xmlDoc.InsertFirstChild(pRoot);
XMLElement * pElement = xmlDoc.NewElement("Stat1");
pElement-> SetText(10);
pRoot->InsertEndChild(pElement);
pElement = xmlDoc.NewElement("Stat2");
pElement->SetText(0.5);
pRoot->InsertEndChild(pElement);
XMLNode * pRoot2 = xmlDoc.NewElement("Head2");
xmlDoc.InsertAfterChild(pRoot, pRoot2);
XMLElement * pElement2 = xmlDoc.NewElement("Stat3");
pElement2-> SetText(10);
pRoot2->InsertEndChild(pElement2);
XMLError eResult = xmlDoc.SaveFile("SavedData.xml");
XMLCheckResult(eResult);
The above code will produce an xml file with following xml structure
<Head>
<Stat1>10</Stat1>
<Stat2>0.5</Stat2>
</Head>
<Head2>
<Stat3>10</Stat3>
</Head2>
But i wanted my desire xml structure to be like
<root>
<Head>
<inner-Head>
<Stat1>10</Stat1>
</inner-Head>
<inner-Head2>
<Stat2>0.5</Stat2>
</inner-Head2>
</Head>
<Head2>
<Stat3>10</Stat3>
</Head2>
</root>
I am new to tinyxml2 and could not find any tinyxml2 tutorials,what i wanted to achieve is to have a node inside a node as shown above.
The process to create nodes and subnodes un tinyxml2 es pretty much recursive: i.e., once you create one, you know how to create the remaining ones.
My advice is to just follow the hierarchy top-down, until you reach the leafs. This way you will only need to use InsertEndChild(). Also, you should use descriptive names for your nodes.
The only difference is that to create the root node, you have to use XMLDoc.InsertEndChild(), while in the remaining cases you receive a pointer to the node, and therefore you have to use the arrow for XMLNode.InsertEndChild().
You want to have a "root" node in the document. Then:
XMLDocument xmlDoc;
XMLNode * nRoot = xmlDoc.NewElement( "root" );
xmlDoc.InsertEndChild( nRoot );
Then you want to have to "Head"'s, hanging from root. So:
XMLNode * nHead = xmlDoc.NewElement( "Head" );
XMLNode * nHead2 = xmlDoc.NewElement( "Head2" );
nRoot->InsertEndChild( nHead );
nRoot->InsertEndChild( nHead2 );
So far so good. Inside "Head", you want two "inner-Heads". Then:
XMLNode * nInnerHead = xmlDoc.NewElement( "inner-Head" );
XMLNode * nInnerHead2 = xmlDoc.NewElement( "inner-Head2" );
nHead->InsertEndChild( nInnerHead );
nHead->InsertEndChild( nInnerHead2 );
And finally, the leafs inside inner-Head and inner-Head2:
XMLElement * pElement = xmlDoc.NewElement( "Stat1" );
pElement-> SetText( 10 );
nInnerHead->InsertEndChild( pElement );
pElement = xmlDoc.NewElement( "Stat2" );
pElement->SetText( 0.5 );
nInnerHead2->InsertEndChild( pElement );
The other branch, in Head2, is even easier, since only one leaf hangs from it:
pElement = xmlDoc.NewElement( "Stat3" );
pElement->SetText( 10 );
nHead2->InsertEndChild( pElement );
And you obtain the desired result:
<root>
<Head>
<inner-Head>
<Stat1>10</Stat1>
</inner-Head>
<inner-Head2>
<Stat2>0.5</Stat2>
</inner-Head2>
</Head>
<Head2>
<Stat3>10</Stat3>
</Head2>
</root>
Hope this helps.