Tinyxml2 append function

460 Views Asked by At

I have been looking for a way to append my xml file using tinyxml2 but couldn't find anything. I would appreciate any help.

Here is my code:

function savedata() {

    XMLNode * pRoot = xmlDoc.NewElement("Cars");
    xmlDoc.InsertFirstChild(pRoot);
    XMLElement * pElement = xmlDoc.NewElement("Brand");

    pElement->SetText("Audi");

    pRoot->InsertEndChild(pElement);

    pElement = xmlDoc.NewElement("type");
    pElement->SetText("4x4");

    pRoot->InsertEndChild(pElement);

    pElement = xmlDoc.NewElement("Date");
    pElement->SetAttribute("day", 26);
    pElement->SetAttribute("month", "April");
    pElement->SetAttribute("Year", 2015);
    pElement->SetAttribute("dateFormat", "26/04/2015");

    pRoot->InsertEndChild(pElement);


    XMLError eResult = xmlDoc.SaveFile("SavedData1.xml");
    XMLCheckResult(eResult);
}

Everytime I run the function, the xml is overwritten and I want to append to the existing file.

My xml file:

<Cars>
    <Brand>Audi</Brand>
    <Whatever>anothercrap</Whatever>
    <Date day="26" month="April" Year="2015" dateFormat="26/04/2015"/>
</Cars>

My root is and I want to append to the existing file. For example,

<Cars>
    <Brand>Audi</Brand>
    <type>4x4</type>
    <Date day="26" month="April" Year="2015" dateFormat="26/04/2015"/>

   <Brand>BMWM</Brand>
   <type>truck</type>
   <Date day="26" month="April" Year="2015" dateFormat="26/04/2015"/>
</Cars>
2

There are 2 best solutions below

0
On

XML is structured data so a textual append would be tricky and possibly error-prone, as you would have to make sure you don't add the root node twice, and that you maintain indentation etc.

What might be easier is to load the XML, parse it with TinyXML, and write it back.

0
On

You can append if you use the FILE overload for xmldoc.Save.

FILE* file = fopen("myfile.xml","a");
xmlDoc.Save(file);
fclose(file);

You just have to be careful when doing this since it will mess up the doc if you're printing multiple root nodes. If you're doing this for logging purposes I would just leave out the root node entirely and just have whatever is reading the log back know to append them or just not even care about proper xml format.