我正在从 string
解析 XML
文件。
我的节点Id
是bar
,我想把它改成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/