gpt4 book ai didi

C++ RapidXML - 编辑 XML 文件中的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:51 24 4
gpt4 key购买 nike

我最近开始使用 RapidXML,解析值没问题(我可以从元素内部获取数据),但我想编辑元素内部的值。

为了这个程序的目的,我想把这个:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>
This is data.
</data>
</root>

进入这个:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>
Edited!
</data>
</root>

我在某处读到 rapidxml::xml_node 有一个 value() 函数来更改元素内部的值,但它似乎不起作用.当我写入文件时,我得到的结果与之前完全相同。这是我的代码:

std::string input_xml = loadFile(filename);
std::vector<char> xml_copy(input_xml.begin(), input_xml.end());
xml_copy.push_back('\0');

rapidxml::xml_document<> doc;

doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_non_destructive>(&xml_copy[0]);
// Also tried with doc.parse<0>(&xml_copy[0]) but no luck

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

root_node->first_node("data")->value(std::string("Edited!").c_str());

std::string data = std::string(xml_copy.begin(), xml_copy.end());

std::ofstream file;
file.open(filename.c_str());
file << data;
file.close();

有什么想法吗?


编辑:

结合已接受的答案,parse() 函数还需要具有 rapidxml::parse_no_data_nodes 标志:

std::string input_xml = TileManager::getData(filename);
std::vector<char> xml_copy(input_xml.begin(), input_xml.end());
xml_copy.push_back('\0');

rapidxml::xml_document<> doc;

doc.parse<rapidxml::parse_no_data_nodes>(&xml_copy[0]); // Notice the flag here
rapidxml::xml_node<>* root_node = doc.first_node("root");

std::string s = "test";
const char * text = doc.allocate_string(s.c_str(), strlen(s.c_str()));

root_node->first_node("data")->value(text);

std::string data;
rapidxml::print(std::back_inserter(data), doc);

std::ofstream file;
file.open(filename.c_str());
file << data;
file.close();

然后它会起作用。

最佳答案

看看这个http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1lifetime_of_source_text .使用 RapidXML,您基本上必须确保您写入文档的任何字符串在文档的生命周期内保持不变。在你的代码中,你正在分配一个临时的,这个临时的在这次调用后将不存在

root_node->first_node("data")->value(std::string("Edited!").c_str());

尝试

std::string new_value = "Edited!";
root_node->first_node("data")->value(new_value.c_str());

它应该适合您。关于将生成的 XML 输出到字符串 http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1printing,也请看一下。

关于C++ RapidXML - 编辑 XML 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15054771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com