XML解析库-pugixml的简单操作

pugixml的主页:http://pugixml.org/

pugixml是轻量级的跨平台且支持xpath的C++ XML解析库

使用pugixml只需要三个文件(pugiconfig.hpp   pugixml.cpp  pugixml.hpp)。

参考文档:https://pugixml.org/docs/quickstart.html

网友中文翻译:https://www.xuebuyuan.com/833087.html

 

进入主题:

加载xml可以使用xm_document类的load_file接口

  • std::string file_path = "C://tmp.xml";
  • pugi::xml_document doc;
  • if(!doc.load_file(file_path.c_str())) return -1;

创建xml:

 1     static const char* kFileName = "D://T.xml";
 2     pugi::xml_document xdoc;
 3     
 4     pugi::xml_node xdec = xdoc.prepend_child(pugi::node_declaration);
 5     xdec.append_attribute("version").set_value("1.0");
 6     xdec.append_attribute("encoding").set_value("utf-8");
 7 
 8     pugi::xml_node xstudents = xdoc.append_child("Students");
 9     xstudents.append_child(pugi::node_comment).set_value("Students!");
10     
11     // Student id = 1234.
12     pugi::xml_node student1 = xstudents.append_child("Student");
13     student1.append_attribute("id").set_value("1234"); // also can use the following style below.
14     //pugi::xml_attribute xstudent_id = xstudent.append_attribute("id");
15     //xstudent_id.set_value("1234");
16 
17     pugi::xml_node xname = student1.append_child("Name");
18     xname.append_child(pugi::node_pcdata).set_value("Tony");
19     pugi::xml_node xage = student1.append_child("Age");
20     xage.append_child(pugi::node_pcdata).set_value("23");
21     pugi::xml_node xschool = student1.append_child("Locate");
22     xschool.append_child(pugi::node_pcdata).set_value("Shanghai");
23 
24     // Student id = 5678.
25     pugi::xml_node student2 = xstudents.append_child("Student");
26     student2.append_attribute("id").set_value("5678");
27 
28     pugi::xml_node name2 = student2.append_child("Name");
29     name2.append_child(pugi::node_pcdata).set_value("Dennis");
30     pugi::xml_node age2 = student2.append_child("Age");
31     age2.append_child(pugi::node_pcdata).set_value("32");
32     pugi::xml_node school2 = student2.append_child("Locate");
33     school2.append_child(pugi::node_pcdata).set_value("Beijing");
34 
35     xdoc.save_file(kFileName);
View Code

解析xml:

 

posted @ 2019-04-29 23:12  fydgo  阅读(713)  评论(0)    收藏  举报