C++工具库之PugiXML使用指南

pugixml是一个非常经典且优秀的C++ XML处理库,很适合用来学习项目结构和高效代码。针对你提到的v1.15版本,我整理了它的详细信息和使用步骤。

📊 项目热度与基础信息

根据开源数据平台的信息,pugixml 是一个高知名度的C++项目。

  • Star 数量约 3,345 (数据随时间略有浮动)。

  • 热度分析 :拥有超过 330个 公共代码库依赖,以及 12个 软件包引用,在vcpkg包管理器的热度排名中位于前5.4%。这些数据表明,它是一个被广泛认可和使用的稳定库。

  • 开源协议 :使用 MIT 许可证。这是一个非常宽松的协议,允许你在商业项目中自由使用、修改和分发,只需保留原作者的版权声明即可。

    MIT 许可证是一种非常宽松的"允许型"(Permissive)开源许可证,它明确允许您将使用该协议的软件应用于商业项目 。

    核心商业权利
    具体来说,在 MIT 许可证下,您拥有以下权利 :

    商业使用:您可以将 PugiXML 库集成到您的商业产品中并出售。

    修改:您可以根据需要修改 PugiXML 的源代码。

    分发:您可以分发包含 PugiXML 的软件,无论是源代码形式还是目标代码形式。

    私用:您可以在内部项目中使用它,无需对外公开。

    必须遵守的唯一条件
    虽然 MIT 许可证非常自由,但它附带一个简单但必须严格遵守的条件:您必须在软件的所有副本或重要组成部分中包含原作者的版权声明和许可证声明 。

💡 主要用途

pugixml 是一个轻量级、简单且快速的C++ XML处理库。它的核心优势在于:

  • DOM-like 接口:提供直观的方式来遍历、修改XML文档树。

  • 极高的解析速度:其非验证性XML解析器性能非常出色,适合性能敏感的场景。

  • XPath 支持:内置了XPath 1.0的实现,可以执行复杂的数据查询。

  • Unicode 支持:完美支持多种Unicode编码,并能自动处理编码转换。

由于其高效和易用的特性,它被广泛应用于各种项目中,例如3D模型导入库 Assimp 、部分 Qt 模块,以及许多自定义的游戏引擎和工具链中。

💡 基于源码数据的核心示例解读

当您获取到本地文档和示例后,可以结合源码中的 resources/ 目录下的XML数据文件(如 tree.xml),重点学习以下几个经典案例。这些案例涵盖了90%的日常使用场景。

示例1:遍历解析树 (samples/traverse.cpp)

  • 目的:学习如何从文件加载XML,并遍历所有节点。

  • 关键步骤与核心代码

    1. 加载XMLpugi::xml_document doc; doc.load_file("tree.xml");

    2. 获取根节点pugi::xml_node root = doc.child("root");

    3. 遍历子节点 :使用 for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling()) 循环处理每个节点。

    4. 访问属性 :通过 node.attribute("name").value() 获取属性值。

  • 应用场景:配置文件读取、数据结构反序列化。

示例2:使用XPath查询 (samples/xpath.cpp)

  • 目的:学习用XPath语言快速定位复杂XML中的元素。

  • 关键步骤与核心代码

    1. 选择单个节点pugi::xpath_node tool = doc.select_node("//tool[@id='1']");

    2. 选择节点集pugi::xpath_node_set tools = doc.select_nodes("//tool[@timeout>0]");

    3. 遍历结果for (auto& node : tools) 处理每一个匹配的节点。

  • 应用场景:数据抽取、自动化测试验证、复杂查询。

示例3:修改XML文档 (samples/modify.cpp)

  • 目的:学习如何添加/删除节点和属性,并保存文档。

  • 关键步骤与核心代码

    1. 添加节点pugi::xml_node node = doc.append_child("new-node");

    2. 添加属性node.append_attribute("name") = "value";

    3. 删除元素doc.remove_child(node_to_delete);

    4. 保存文档doc.save_file("output.xml");

  • 应用场景:动态生成配置文件、XML编辑器、数据持久化。

💡 windows x64依赖库及头文件

include:pugiconfig.hpp pugixml.hpp

lib:pugixml.lib

💡 使用案例源码

复制代码
#include <iostream>
#include "pugixml/pugixml.hpp"


int traverse_base()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    pugi::xml_node tools = doc.child("Profile").child("Tools");

    // tag::basic[]
    for (pugi::xml_node tool = tools.first_child(); tool; tool = tool.next_sibling())
    {
        std::cout << "Tool:";

        for (pugi::xml_attribute attr = tool.first_attribute(); attr; attr = attr.next_attribute())
        {
            std::cout << " " << attr.name() << "=" << attr.value();
        }

        std::cout << std::endl;
    }
    // end::basic[]

    std::cout << std::endl;

    // tag::data[]
    for (pugi::xml_node tool = tools.child("Tool"); tool; tool = tool.next_sibling("Tool"))
    {
        std::cout << "Tool " << tool.attribute("Filename").value();
        std::cout << ": AllowRemote " << tool.attribute("AllowRemote").as_bool();
        std::cout << ", Timeout " << tool.attribute("Timeout").as_int();
        std::cout << ", Description '" << tool.child_value("Description") << "'\n";
    }
    // end::data[]

    std::cout << std::endl;

    // tag::contents[]
    std::cout << "Tool for *.dae generation: " << tools.find_child_by_attribute("Tool", "OutputFileMasks", "*.dae").attribute("Filename").value() << "\n";

    for (pugi::xml_node tool = tools.child("Tool"); tool; tool = tool.next_sibling("Tool"))
    {
        std::cout << "Tool " << tool.attribute("Filename").value() << "\n";
    }
    // end::contents[]
}

int traverse_iter()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    pugi::xml_node tools = doc.child("Profile").child("Tools");

    // tag::code[]
    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;
    }
    // end::code[]
}

int xpath_query()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    // tag::code[]
        // Select nodes via compiled query
    pugi::xpath_query query_remote_tools("/Profile/Tools/Tool[@AllowRemote='true']");

    pugi::xpath_node_set tools = query_remote_tools.evaluate_node_set(doc);
    std::cout << "Remote tool: ";
    tools[2].node().print(std::cout);

    // Evaluate numbers via compiled query
    pugi::xpath_query query_timeouts("sum(//Tool/@Timeout)");
    std::cout << query_timeouts.evaluate_number(doc) << std::endl;

    // Evaluate strings via compiled query for different context nodes
    pugi::xpath_query query_name_valid("string-length(substring-before(@Filename, '_')) > 0 and @OutputFileMasks");
    pugi::xpath_query query_name("concat(substring-before(@Filename, '_'), ' produces ', @OutputFileMasks)");

    for (pugi::xml_node tool = doc.first_element_by_path("Profile/Tools/Tool"); tool; tool = tool.next_sibling())
    {
        std::string s = query_name.evaluate_string(tool);

        if (query_name_valid.evaluate_boolean(tool)) std::cout << s << std::endl;
    }
    // end::code[]
}

int xpath_error()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    // tag::code[]
        // Exception is thrown for incorrect query syntax
    try
    {
        doc.select_nodes("//nodes[#true()]");
    }
    catch (const pugi::xpath_exception& e)
    {
        std::cout << "Select failed: " << e.what() << std::endl;
    }

    // Exception is thrown for incorrect query semantics
    try
    {
        doc.select_nodes("(123)/next");
    }
    catch (const pugi::xpath_exception& e)
    {
        std::cout << "Select failed: " << e.what() << std::endl;
    }

    // Exception is thrown for query with incorrect return type
    try
    {
        doc.select_nodes("123");
    }
    catch (const pugi::xpath_exception& e)
    {
        std::cout << "Select failed: " << e.what() << std::endl;
    }
    // end::code[]
}

int xpath_variables()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    // tag::code[]
        // Select nodes via compiled query
    pugi::xpath_variable_set vars;
    vars.add("remote", pugi::xpath_type_boolean);

    pugi::xpath_query query_remote_tools("/Profile/Tools/Tool[@AllowRemote = string($remote)]", &vars);

    vars.set("remote", true);
    pugi::xpath_node_set tools_remote = query_remote_tools.evaluate_node_set(doc);

    vars.set("remote", false);
    pugi::xpath_node_set tools_local = query_remote_tools.evaluate_node_set(doc);

    std::cout << "Remote tool: ";
    tools_remote[2].node().print(std::cout);

    std::cout << "Local tool: ";
    tools_local[0].node().print(std::cout);

    // You can pass the context directly to select_nodes/select_node
    pugi::xpath_node_set tools_local_imm = doc.select_nodes("/Profile/Tools/Tool[@AllowRemote = string($remote)]", &vars);

    std::cout << "Local tool imm: ";
    tools_local_imm[0].node().print(std::cout);
    // end::code[]
}

int xpath_select()
{
    pugi::xml_document doc;
    if (!doc.load_file("D:/Code/TestBin/appdata/testdata/xgconsole.xml")) return -1;

    // tag::code[]
    pugi::xpath_node_set tools = doc.select_nodes("/Profile/Tools/Tool[@AllowRemote='true' and @DeriveCaptionFrom='lastparam']");

    std::cout << "Tools:\n";

    for (pugi::xpath_node_set::const_iterator it = tools.begin(); it != tools.end(); ++it)
    {
        pugi::xpath_node node = *it;
        std::cout << node.node().attribute("Filename").value() << "\n";
    }

    pugi::xpath_node build_tool = doc.select_node("//Tool[contains(Description, 'build system')]");

    if (build_tool)
        std::cout << "Build tool: " << build_tool.node().attribute("Filename").value() << "\n";
    // end::code[]
}

int modify_add()
{
    pugi::xml_document doc;

    // tag::code[]
    // add node with some name
    pugi::xml_node node = doc.append_child("node");

    // add description node with text child
    pugi::xml_node descr = node.append_child("description");
    descr.append_child(pugi::node_pcdata).set_value("Simple node");

    // add param node before the description
    pugi::xml_node param = node.insert_child_before("param", descr);

    // add attributes to param node
    param.append_attribute("name") = "version";
    param.append_attribute("value") = 1.1;
    param.insert_attribute_after("type", param.attribute("name")) = "float";
    // end::code[]

    doc.print(std::cout);

    return 0;
}

int modify_base()
{
    pugi::xml_document doc;
    if (!doc.load_string("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;

    // tag::node[]
    pugi::xml_node node = doc.child("node");

    // change node name
    std::cout << node.set_name("notnode");
    std::cout << ", new node name: " << node.name() << std::endl;

    // change comment text
    std::cout << doc.last_child().set_value("useless comment");
    std::cout << ", new comment text: " << doc.last_child().value() << std::endl;

    // we can't change value of the element or name of the comment
    std::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl;
    // end::node[]

    // tag::attr[]
    pugi::xml_attribute attr = node.attribute("id");

    // change attribute name/value
    std::cout << attr.set_name("key") << ", " << attr.set_value("345");
    std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl;

    // we can use numbers or booleans
    attr.set_value(1.234);
    std::cout << "new attribute value: " << attr.value() << std::endl;

    // we can also use assignment operators for more concise code
    attr = true;
    std::cout << "final attribute value: " << attr.value() << std::endl;
    // end::attr[]
    return 0;
}

int main() 
{
    //pugi::xml_document doc;
    //// 加载XML文件 (这里假设同级目录下有一个名为 "data.xml" 的文件)
    //pugi::xml_parse_result result = doc.load_file("D:/Code/TestBin/appdata/testdata/utftest_utf8.xml");

    //if (!result) {
    //    std::cerr << "文件加载失败: " << result.description() << std::endl;
    //    return -1;
    //}

    //// 使用XPath查询所有timeout大于0的tool节点
    //pugi::xpath_node_set tools = doc.select_nodes("//tool[@timeout > 0]");

    //for (pugi::xpath_node node : tools) {
    //    pugi::xml_node tool = node.node();
    //    std::cout << "工具名称: " << tool.attribute("name").value()
    //        << ", 超时时间: " << tool.attribute("timeout").as_int() << std::endl;
    //}

    modify_add();
    std::cin.get();
    return 0;
}
相关推荐
毕设源码-钟学长1 小时前
【开题答辩全过程】以 哈尔滨市小酒窝APP为例,包含答辩的问题和答案
java
人道领域2 小时前
MyBatisPlus高效开发实战指南
java·开发语言·数据库
tankeven2 小时前
HJ98 喜欢切数组的红
c++·算法
adore.9682 小时前
2.22 oj基础92 93 94+U12
数据结构·c++·算法
消失的旧时光-19432 小时前
C++ 多线程与并发系统取向(四)—— std::condition_variable:线程协作与生产者消费者模型(类比 Java wait/notify)
开发语言·c++
AALoveTouch2 小时前
逆向利器:Frida Hook
java·python
春和景明3602 小时前
费曼学习法
java
精彩极了吧2 小时前
C++基础知识-(②)面向对象(上)
c++·类和对象·封装·this指针·类的默认成员函数·赋值运算符重载
三水彡彡彡彡2 小时前
深入理解指针:常量、函数与数组
c++·学习