1、rapidxml修改節點的value,修改之后,序列化還是原來的值,具體原因是什么,要看rapidxml是怎么實現的。如下:
void TestRapidXml() { char* xmlContent = new char[1024]; sprintf(xmlContent,"<root><head>aaa</head><body x=\"10\">bbb</body></root>"); xml_document<> xmlDoc; xmlDoc.parse<0>(xmlContent); xml_node<>* body = xmlDoc.first_node()->first_node("body"); body->value("ccc"); xml_attribute<>* x = body->first_attribute("x"); x->value("20"); string xmlStr = ""; // xmlString為 <root><head>aaa</head><body x=\"20\">bbb</body></root> // 也就是說,attr的value可以修改成功,而node的value還是舊值。
rapidxml::print(std::back_inserter(xmlStr),xmlDoc,0); delete []xmlContent; }
2、怎么解決上面的問題,笨辦法,既然不能修改,我就添加一個新的,刪除老的。如下:
void TestRapidXml() { char* xmlContent = new char[1024]; sprintf(xmlContent,"<root><head>aaa</head><body x=\"10\">bbb</body></root>"); xml_document<> xmlDoc; xmlDoc.parse<0>(xmlContent); xml_node<>* root = xmlDoc.first_node(); xml_node<>* body = root->first_node("body"); xml_node<>* newBody = xmlDoc.allocate_node(node_element, xmlDoc.allocate_string("body"),xmlDoc.allocate_string("ccc")); // 插入一個新的body
root->insert_node(body,newBody); // 復制老body的attr
for(xml_attribute<>* attr = body->first_attribute();attr!=NULL;attr=attr->next_attribute()) { xml_attribute<>* copy = xmlDoc.allocate_attribute(xmlDoc.allocate_string(attr->name()), xmlDoc.allocate_string(xmlDoc.allocate_string(attr->value()))); newBody->append_attribute(copy); } // 刪除老的body
root->remove_node(body); string xmlStr = ""; // xmlString為 <root><head>aaa</head><body x=\"10\">ccc</body></root>
rapidxml::print(std::back_inserter(xmlStr),xmlDoc,0); delete []xmlContent; }
3、還有一個辦法,就是使用 xmlDoc.parse<parse_no_data_nodes>(xmlContent); 如下:
void TestRapidXml() { char* xmlContent = new char[1024]; sprintf(xmlContent,"<root><head>aaa</head><body x=\"10\">bbb</body></root>"); xml_document<> xmlDoc; //xmlDoc.parse<0>(xmlContent);
xmlDoc.parse<parse_no_data_nodes>(xmlContent); xml_node<>* body = xmlDoc.first_node()->first_node("body"); body->value("ccc"); xml_attribute<>* x = body->first_attribute("x"); x->value("20"); string xmlStr = ""; // xmlString為 <root><head>aaa</head><body x=\"20\">ccc</body></root>
rapidxml::print(std::back_inserter(xmlStr),xmlDoc,0); delete []xmlContent; }