rapidxml 修改节点值

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



转载于:https://my.oschina.net/mjRao/blog/415067

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值