C++/RapidXML : Edit node and write to a new XML file doesn't have the updated nodes

标签 c++ rapidxml

我正在从 string 解析 XML 文件。 我的节点Idbar,我想把它改成foo然后写入文件。

写入文件后,文件仍然有bar,而不是foo

#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
void main()
{
    std::string newXml = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?><Parent><FileId>fileID</FileId><IniVersion>2.0.0</IniVersion><Child><Id>bar</Id></Child></Parent>";

    xml_document<> doc;
    xml_node<> * root_node;

    std::string str = newXml;
    std::vector<char> buffer(str.begin(), str.end());
    buffer.push_back('\0');

    doc.parse<0>(&buffer[0]);

    root_node = doc.first_node("Parent");

    xml_node<> * node = root_node->first_node("Child");
    xml_node<> * xml = node->first_node("Id");
    xml->value("foo"); // I want to change my id from bar to foo!!!!

    std::ofstream outFile("output.xml");
    outFile << doc; // after I write to file, I still see the ID as bar
}

我在这里错过了什么?

最佳答案

问题在于数据布局。在 node_element 下节点 xml还有一个node_data包含 "bar" 的节点. 您发布的代码也无法编译。在这里,我编译了您的代码并展示了如何修复它:

#include <vector>
#include <iostream>
#include "rapidxml.hpp"
#include "rapidxml_print.hpp"

int main()
{
    std::string newXml = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?><Parent><FileId>fileID</FileId><IniVersion>2.0.0</IniVersion><Child><Id>bar</Id></Child></Parent>";

    rapidxml::xml_document<> doc;

    std::string str = newXml;
    std::vector<char> buffer(str.begin(), str.end());
    buffer.push_back('\0');

    doc.parse<0>(&buffer[0]);

    rapidxml::xml_node<>* root_node = doc.first_node("Parent");

    rapidxml::xml_node<>* node = root_node->first_node("Child");
    rapidxml::xml_node<>* xml = node->first_node("Id");
    // xml->value("foo"); // does change something that isn't output!!!!

    rapidxml::xml_node<> *real_thing = xml->first_node();
    if (real_thing != nullptr                         // these checks just demonstrate that
       &&  real_thing->next_sibling() == nullptr      // it is there and how it is located
       && real_thing->type() == rapidxml::node_data)  // when element does contain text data 
    {
        real_thing->value("yuck");  // now that should work
    }

    std::cout << doc; // lets see it
}

所以它输出:

<Parent>
    <FileId>fileID</FileId>
    <IniVersion>2.0.0</IniVersion>
    <Child>
        <Id>yuck</Id>
    </Child>
</Parent>

看到了吗?请注意,数据在解析期间的布局方式取决于您提供给解析的标志。例如,如果您首先输入 doc.parse<rapidxml::parse_fastest>那么解析器将不会创建这样的 node_data节点,然后更改 node_element数据(就像你第一次尝试的那样)会起作用(而我上面所做的不会)。从 manual 中阅读详细信息.

关于C++/RapidXML : Edit node and write to a new XML file doesn't have the updated nodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170187/

相关文章:

c++ - 如何解决 RapidXML 字符串所有权问题?

c++ - Boost 编译在 ubuntu 服务器 14.04 上失败

c++ - C++中lambda函数的继承参数

c++ - RapidXml 和内存池

c++ - RapidXml 无法解析包含 unicode 的 xml

c++ - 如何使用 rapidxml 读取嵌套的 xml

c++ - 编译我的第一个 C++ 程序时遇到问题

c++ - PC Lint 并检查可能的 nullptr

c++ - 大 float 的C++库

c++ - 可能是 rapidxml 中的错误 - 但我不确定如何修复