config.xml文件内容:
<cfg>
<sys>
<ip>192.168.1.22</ip>
<netmask>255.255.0.0</netmask>
<gateway>169.254.1.1</gateway>
<mac>00:00:00:00:00:01</mac>
</sys>
</cfg>
譬如现在要修改ip节点值为169.254.1.20,代码如下
#include <iostream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"
int main(int argc,char **argv)
{
rapidxml::file<> file("config.xml");
rapidxml::xml_document<> doc;
//doc.parse<0>(file.data());
doc.parse<rapidxml::parse_no_data_nodes>(file.data());
std::cout << doc.name() << std::endl;
//获取根节点
rapidxml::xml_node<> *root = doc.first_node();
std::cout << root->name() << std::endl;
rapidxml::xml_node<> *node = root->first_node("sys");
std::cout << node->name() << std::endl;
//char *str = doc.allocate_string("192.168.1.20");
std::string str = "169.254.1.20";
node->first_node("ip")->value(str.c_str());
std::cout << node->first_node("ip")->value() << std::endl;
std::string text;
rapidxml::print(std::back_inserter(text), doc, 0);
std::cout << text << std::endl;
std::ofstream out("config.xml");
out << doc;
return 0;
}
很多人在修改在序列化xml时用
doc.parse<0>(file.data());
这个是无法修改值的。必须使用如下
doc.parse<rapidxml::parse_no_data_nodes>(file.data());
具体参加如下描述
Question:
Printing a document having a node with a modified value yields the wrong output. Example:
xml_document<char> doc;
doc.parse<0>(doc.allocate_string("<test>old</test>"));
doc.first_node()->value(doc.allocate_string("new"));
rapidxml::print(cout, doc);
This will print "<test>old</test>" and not "<test>new</test>" as you would expect
Answer:
This is by design, although a little awkward.
The problem is that value of node is only a "shortcut" for the real data, which is stored in child data nodes of the node.
Child data nodes always take precedence over "value" of a node - to change the data you must do either one of the following:
- change the data in child data node(s), not in the value of parent node
- tell parser that you do not want to have data nodes generated (parse_no_data_nodes), in which case you can just change the value
相关连接:
http://sourceforge.net/p/rapidxml/bugs/3/
http://www.setnode.com/blog/quick-notes-on-how-to-use-rapidxml/
http://stackoverflow.com/questions/15054771/c-rapidxml-edit-values-in-the-xml-file