C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ PugiXML使用

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

作者:tianzhiyi1989sq

pugixml是一个高效、易用的C++ XML处理库,适用于各种项目,如游戏引擎和工具链,项目热度高,依赖广泛,使用MIT许可证,通过学习示例,可以掌握遍历、查询和修改XML文档的方法,感兴趣的朋友跟随小编一起看看吧

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

📊 项目热度与基础信息

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

MIT 许可证是一种非常宽松的“允许型”(Permissive)开源许可证,它明确允许您将使用该协议的软件应用于商业项目 。
核心商业权利
具体来说,在 MIT 许可证下,您拥有以下权利 :
商业使用:您可以将 PugiXML 库集成到您的商业产品中并出售。
修改:您可以根据需要修改 PugiXML 的源代码。
分发:您可以分发包含 PugiXML 的软件,无论是源代码形式还是目标代码形式。
私用:您可以在内部项目中使用它,无需对外公开。
必须遵守的唯一条件
虽然 MIT 许可证非常自由,但它附带一个简单但必须严格遵守的条件:您必须在软件的所有副本或重要组成部分中包含原作者的版权声明和许可证声明 。

💡 主要用途

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

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

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

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

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

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

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

💡 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;
}

到此这篇关于C++工具库之PugiXML使用实战指南的文章就介绍到这了,更多相关C++ PugiXML使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文