[英]Tinyxml2 append function
我一直在寻找一种使用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>
XML是结构化的数据,因此文本附加会很棘手,并且可能容易出错,因为您必须确保不要两次添加根节点,并且要保持缩进等。
可能更容易的是加载XML,用TinyXML解析,然后写回。
如果对xmldoc.Save使用FILE重载,则可以追加。
FILE* file = fopen("myfile.xml","a");
xmlDoc.Save(file);
fclose(file);
您只需要在执行此操作时小心一点,因为如果您要打印多个根节点,它将使文档混乱。 如果您出于记录目的而执行此操作,那么我将完全忽略根节点,并且仅知道正在读取回传的内容以追加它们,甚至根本不关心正确的xml格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.