【问题标题】:Tinyxml2 append functionTinyxml2 附加功能
【发布时间】:2015-05-26 14:07:22
【问题描述】:

我一直在寻找一种使用 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>

【问题讨论】:

    标签: c++ tinyxml2


    【解决方案1】:

    XML 是结构化数据,因此文本追加会很棘手并且可能容易出错,因为您必须确保不添加两次根节点,并且保持缩进等。

    可能更容易的是加载 XML,用 TinyXML 解析,然后写回。

    【讨论】:

      【解决方案2】:

      如果您对 xmldoc.Save 使用 FILE 重载,则可以追加。

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

      您在执行此操作时必须小心,因为如果您要打印多个根节点,它会弄乱文档。如果您这样做是出于日志记录的目的,我会完全忽略根节点,而只是让正在读取日志的任何内容都知道附加它们,或者甚至不关心正确的 xml 格式。

      【讨论】:

        猜你喜欢
        • 2015-12-31
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多