pugixml基础信息留存

本文介绍PugiXML的使用技巧,包括配置unicode支持、获取属性值、节点操作等,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

最近想找一个合适的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']");//查询属性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值