pugixml 1.8快速入门

来源:互联网 发布:微信玩骰子作弊软件 编辑:程序博客网 时间:2024/04/28 11:13

pugixml是一个轻量级的C ++ XML操作库。

Pugixml包含三个文件pugixml.cpp、 pugixml.hpp 、 pugiconfig.hpp。


pugixml.hpp是主头文件,要使用pugixml类及其方法必须将它包含到工程中。

pugiconfig.hpp是pugixml的配置文件,例如配置是否使用宽字符模式(#define PUGIXML_WCHAR_MODE)

pugixml.cpp是源文件,该文件需设置为不使用预编译头。



xml_document是整个文档结构的管理者,其功能包含加载/保存文档等,销毁它将销毁整个文档。

xml_node是文档节点的句柄; 它可以指向文档中的任何节点,销毁它不会销毁节点本身。

xml_attribute是XML属性的句柄。


加载文件

pugi::xml_document doc;pugi::xml_parse_result result = doc.load_file(_T("D:\\XXX.xml"));

从可变内存加载doc.load_buffer_inplace,从固定内存加载doc.load_buffer,从streams加载doc.load


使用节点名获取节点句柄

pugi::xml_node tool ;tool = tools.child("Tool");tool = tool.next_sibling("Tool");


获取属性/节点名

tool.name();

获取属性值value()

tool.attribute(_T("XXX")).value();tool.attribute(_T("XXX")).as_double();tool.attribute(_T("XXX")).as_int();tool.attribute(_T("XXX")).as_bool();……


迭代器

for (pugi::xml_node_iterator it = tools.begin(); it != tools.end(); ++it){    std::cout << "Tool:";    for (pugi::xml_attribute_iterator ait = it->attributes_begin(); ait != it->attributes_end(); ++ait)    {        std::cout << " " << ait->name() << "=" << ait->value();    }    std::cout << std::endl;}


增删节点

tool.append_child(_T("Layer"));tool.remove_child(_T("Layer"));

增删属性

tool.append_attribute(_T("Name"));tool.remove_attribute(_T("Name"));

添加声明

pugi::xml_node pre = doc.prepend_child(pugi::node_declaration);pre.append_attribute("version") = "1.0";pre.append_attribute("encoding") = "utf-8";


添加注释
pugi::xml_node node_Comment = Tool.append_child(pugi::node_comment);node_Comment .set_value("XXXX");


保存文件

doc.save_file(_T("D:\\XXX.xml"));