问题:
最近想找一个合适的XML解析器,用过tinyxml,对unicode中文支持是真的不友好。试用了下rapidxml,感觉太麻烦了。最后找到了pugixml,用起来是真清爽,留存记录下,以便后续查看。
解决方案
准备工作
#include “pugixml.hpp”
打开pugiconfig.hpp的代码
值得说明的是pugiconfig.hpp配置文件,里面定义了许多宏,如:
PUGIXML_WCHAR_MODE:开启unicode支持;
PUGIXML_COMPACT:支持紧凑型内存管理布局;
PUGIXML_NO_XPATH:不需要xpath支持,可减少pugixml编译为库的体积;
PUGIXML_NO_STL:不使用STL支持,对于不想使用STL环境下比较有用;
PUGIXML_NO_EXCEPTIONS:不允许抛出异常;
PUGIXML_API:编译导出为DLL;
PUGIXML_MEMORY_PAGE_SIZE:内存页大小;
PUGIXML_HAS_LONG_LONG:支持long long数据类型;
PUGIXML_HEADER_ONLY:只包含头文件,这样头文件内部会自己包含cpp文件;
// Uncomment this to enable wchar_t mode
#define PUGIXML_WCHAR_MODE
获取属性值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"));
添加声明
pugi::xml_node pre = doc.prepend_child(pugi::node_declaration);
pre.append_attribute(L"version") = L"1.0";
pre.append_attribute(L"encoding") = L"utf-8";
添加注释
pugi::xml_node node_Comment = Tool.append_child(pugi::node_comment);
node_Comment .set_value(“XXXX”);
查询
//通过xpath1.0语法
pugi::xpath_node build_tool = doc.select_node(L"//Tool[contains(Description, 'build system')]");//查询节点
pugi::xpath_node del_tool = doc.select_node(L"Profile/Tools/Tool[@OutputFileMasks='*.dae']");//查询属性