我一直在寻找一种使用tinyxml2附加xml文件的方法,但什么也找不到。如果有任何帮助,我将不胜感激。
下面是我的代码:
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);
}每次运行该函数时,xml都会被覆盖,并且我希望将其附加到现有文件中。
我的xml文件:
<Cars>
<Brand>Audi</Brand>
<Whatever>anothercrap</Whatever>
<Date day="26" month="April" Year="2015" dateFormat="26/04/2015"/>
</Cars>我的根是,我想要追加到现有的文件。例如,
<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>发布于 2015-05-26 23:21:34
XML是结构化数据,因此文本追加将很棘手,而且可能容易出错,因为您必须确保不会添加两次根节点,并保持缩进等。
更简单的方法可能是加载XML,用TinyXML解析它,然后写回它。
发布于 2019-05-04 20:14:54
如果对xmldoc.Save使用文件重载,则可以追加。
FILE* file = fopen("myfile.xml","a");
xmlDoc.Save(file);
fclose(file);执行此操作时必须小心,因为如果打印多个根节点,则会使文档变得混乱。如果您这样做是为了记录日志,那么我将完全省略根节点,让正在读回日志的内容追加它们,或者根本不关心正确的xml格式。
https://stackoverflow.com/questions/30460949
复制相似问题