代码之家  ›  专栏  ›  技术社区  ›  waas1919

C++/RapidXML:编辑节点并写入新的XML文件没有更新的节点

  •  1
  • waas1919  · 技术社区  · 9 年前

    我正在分析一个 XML 文件来自 string 我的节点 Id 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
    }
    

    我错过了什么?

    1 回复  |  直到 9 年前
        1
  •  2
  •   Öö Tiib    9 年前

    问题在于数据的布局。在下面 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_元素 manual .