【问题标题】:Insert element (TinyXml)插入元素 (TinyXml)
【发布时间】:2018-12-11 12:01:58
【问题描述】:

我想在 xml 文件中添加元素。谁能帮我做这件事?

以下是我的代码试用。

 <?xml version="1.0" encoding="UTF-8" ?>
    <category1>
        <category2 name="1">1.79639 0.430521</category2 >
        <category2 name="2">2.06832 0.652695</category2 >
        <category2 name="3">1.23123 0.111212</category2 >    <-- new
    </category1>

代码:

 if (doc.LoadFile()) {
                TiXmlHandle docHandle(&doc);
                TiXmlElement* fileLog = docHandle.FirstChild("category1").ToElement();
                if (fileLog) {
                    TiXmlElement newCategory2("category2");
                    newCategory2.SetAttribute("name", "5");
                    fileLog->InsertEndChild(newCategory2);
                }
            }

希望得到任何人的帮助。

【问题讨论】:

  • 此问题分解为“读取 XML 文件”、在 &lt;category1&gt; 中添加 &lt;category2&gt; 元素和“将 XML 写回文件”。你已经实现了哪些位,你在哪里卡住了?
  • @Botje,已更新
  • 好的,这段代码有什么问题?它会崩溃吗?它会给出编译器错误吗?根据我的阅读,您最好使用new 在堆上分配newCategory2
  • @Botje:InsertEndChild 将使用 TiXml 内存模型创建一个新节点。该节点将从输入节点构建(复制)。

标签: c++ tinyxml


【解决方案1】:

TiXML 不接受 XML 标记之间的空格 &lt;/category2 &gt;,它必须是 &lt;/category2&gt;。您的 LoadFile 将返回 false 并且不会插入节点。

以下代码按预期工作:

    const char * szTiXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
        "<category1>"
        "<category2 name=\"1\">1.79639 0.430521</category2>"
        "<category2 name=\"2\">2.06832 0.652695</category2>"
        "<category2 name=\"3\">1.23123 0.111212</category2>"
        "</category1>";

    TiXmlDocument doc;
    doc.Parse( szTiXML );
    //if (doc.LoadFile()) 
    {
        TiXmlHandle docHandle(&doc);
        TiXmlElement* fileLog = docHandle.FirstChild("category1").ToElement();
        if (fileLog) {
            TiXmlElement newCategory2("category2");
            TiXmlText myText("Hello From SO");

            newCategory2.SetAttribute("name", "5");
            newCategory2.InsertEndChild(myText);

            fileLog->InsertEndChild(newCategory2);
        }

        doc.Print(stdout);
    }

输出:

<?xml version="1.0" encoding="UTF-8" ?>
<category1>
    <category2 name="1">1.79639 0.430521</category2>
    <category2 name="2">2.06832 0.652695</category2>
    <category2 name="3">1.23123 0.111212</category2>
    <category2 name="5">Hello From SO</category2>
</category1>

【讨论】:

  • 我如何获得下一个:text
  • @bobtorus:我编辑了我的答案。您可以根据需要在应用程序中添加文本。
猜你喜欢
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2011-05-09
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多