pugixml 是一个广受好评的 C++ XML 解析库,其相对优势包括但不限于以下几个方面:
pugixml 以其高效、易用、全面的功能和良好的跨平台能力成为 C++ 开发者处理 XML 数据的理想选择之一。
链接:
使用Pugixml库,轻松处理XML文件-CSDN博客
pugixml github下载地址:
使用Pugixml库,轻松处理XML文件-CSDN博客
重点:
读取如下一个xml
代码:
#include <map>
#include "pugixml.hpp"
#include <filesystem>
#include <map>
struct MenuItem
{
std::wstring s_name; //中文名称
std::wstring s_cmd; //命令名称
int s_picIndex; //图片资源索引
int s_option; //布置类型
MenuItem()
{
s_name = std::wstring{};
s_cmd = std::wstring{};
s_picIndex = 0;
s_option = 0;
}
MenuItem(const MenuItem& data)
{
s_name = data.s_name;
s_cmd = data.s_cmd;
s_picIndex = data.s_picIndex;
s_option = data.s_option;
}
};
struct MenuItemInfo
{
std::vector<MenuItem> s_itemInfo;
bool s_enable{ true };
};
bool isFileExistsWithFS(const std::wstring& filename) {
namespace fs = std::filesystem;
return fs::exists(fs::path(filename));
}
void GetCommonDataFromXmlNodeInfo(const pugi::xml_node& node, MenuItemInfo& info, bool option = false)
{
auto items = node.children(L"item");
for (auto& var : items)
{
MenuItem data;
data.s_name = var.attribute(L"name").as_string();
data.s_cmd = var.attribute(L"cmd").as_string();
data.s_picIndex = var.attribute(L"picIndex").as_int();
if (option)
{
data.s_option = var.attribute(L"option").as_int();
}
info.s_itemInfo.emplace_back(data);
}
}
int main()
{
std::wstring n_lastCmd = L"重复"; //重复
std::wstring n_deselect = L"取消选择"; //取消选择
std::wstring n_do = L"do"; //do
std::wstring n_changeCmd = L"修改命令";
std::wstring n_calculate = L"计算操作";
std::wstring n_calset = L"计算设置";
std::wstring n_commandOp = L"通用操作";
std::wstring n_visible = L"显隐操作";
MenuItemInfo m_lastCmd; //重复上一个命令
MenuItemInfo m_deselect; //取消选择
MenuItemInfo m_do; //undo/redo
MenuItemInfo m_changeCmd; //修改命令
MenuItemInfo m_calculate; //计算操作
MenuItemInfo m_calset; //计算设置
MenuItemInfo m_commandOp; //通用操作
MenuItemInfo m_visible; //显隐控制
std::map<std::wstring, MenuItemInfo&> commonGroup{ {n_lastCmd ,m_lastCmd},{n_deselect,m_deselect}, {n_do,m_do} ,
{n_calculate,m_calculate} ,{n_calset,m_calset} ,{n_commandOp,m_commandOp} ,{n_visible,m_visible} };
std::wstring menuPath = L".//File//xmlpugi.xml";
pugi::xml_document xmlDoc;
if (!isFileExistsWithFS(menuPath))
{
return 0;
}
else
{
xmlDoc.load_file(menuPath.c_str(), pugi::parse_default, pugi::encoding_utf8);
pugi::xml_node rootNode = xmlDoc.child(L"root");
if (rootNode.empty())
{
return 0;
}
auto groupNode = rootNode.children(L"group");
for (auto& node : groupNode)
{
std::wstring groupName = node.attribute(L"groupName").as_string();
auto iter = commonGroup.find(groupName);
if (iter != commonGroup.end())
{
GetCommonDataFromXmlNodeInfo(node, iter->second);
}
}
}
return 0;
}