reference:http://www.gerald-fahrnholz.eu/sw/DocGenerated/HowToUse/html/group___grp_pugi_xml.html
xml文件,假設名爲hello.xml:
<?xml version='1.0' encoding='UTF-8'?>
<scenarios map="hangzhou">
<point x="1" y="1"/>
<point x="2" y="2"/>
<point x="3" y="3"/>
</scenarios>
1、讀xml
#include <pugixml.hpp>
void ReadXml(const char* filename) {
pugi::xml_document doc;
if (!doc.load_file(filename)) {
std::cerr << "fail to read" << std::endl;
}
pugi::xml_node root_node= doc_.child("scenarios");
if(root_node.empty()) {
std::cerr << "no child named scenarios in document";
return;
}
pugi::xml_attribute map_attr = root_node.attribute("map");
if(!map_attr.empty()) {
std::cout << "map: " << map_attr.as_string();
}
for(pugi::xmlnode point_node = root_node.first_child(); point_node != NULL; point_node = point_node.next_sibling()) {
std::cout << point_node.attribute("x").as_double() << " " << point_node.attribute("y").as_double() << std::endl;
}
}
2、寫xml
#include <pugixml.hpp>
void WriteXml(const char* filename) {
pugi::xml_document doc;
pugi::xml_node declaration_node = doc_.append_child(pugi::node_declaration);
declaration_node.append_attribute("version") = "1.0";
declaration_node.append_attribute("encoding") = "UTF-8";
pugi::xml_node root_node = doc.append_child("scenarios");
root_node.append_attribute("map") = "hangzhou";
for(int i = 1; i <= 3; i++) {
pugi::xml_node point_node = root_node.append_child("point");
point_node.append_attribute("x") = i;
point_node.append_attribute("y") = i;
}
doc.save_file(filename);
}
3、一些需要注意的問題
(1)在讀xml的時候,要確保在完成所有需要的read動作之前,pugi::xml_document對象始終在內存中沒有被銷燬,否則即使手裏還有pugi::xml_node對象,指向的空間也已經隨着xml_document的析構被釋放了。
(2)xml_node中實際上只保存了指向相應數據空間的一個指針,所以即使是複製了一個xml_node,然後調用其append_child()等修改操作,對原始的xml_node也是生效的