在 C++ 中处理 XML:库、解析与创建 XML 文档

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 C++ 中处理 XML:用于解析和创建 XML 文档的库概览



XML(可扩展标记语言)仍然是存储和传输结构化数据的流行格式,特别是在配置文件、Web 服务(SOAP、XML-RPC)以及系统间数据交换中。C++ 本身没有内置的 XML 支持(除了已过时的 MSXML),因此开发者会求助于第三方库。在本文中,我们将介绍三种最流行且轻量级的 C++ XML 处理库:TinyXML-2、PugiXML 和 RapidXML。您将了解如何安装它们,如何解析和创建 XML 文档,并对它们的性能和易用性进行比较。



1. TinyXML-2



TinyXML-2 是一个简单、极简的库,仅由两个文件(tinyxml2.h 和 tinyxml2.cpp)组成。它非常适合那些不需要高性能但注重集成简便性的小型项目。该库采用 Zlib 许可,允许在商业项目中自由使用。



安装

从官方仓库复制 tinyxml2.h 和 tinyxml2.cpp 文件到您的项目中并包含它们。无需任何额外的依赖项。



示例:读取 XML

#include "tinyxml2.h"#include <iostream>

int main() { tinyxml2::XMLDocument doc; doc.LoadFile("config.xml");

tinyxml2::XMLElement* root = doc.RootElement(); if (root) { const char* value = root->FirstChildElement("setting")->GetText(); std::cout << "Setting: " << value << std::endl; } return 0;}


示例:创建 XML

#include "tinyxml2.h"

int main() { tinyxml2::XMLDocument doc; tinyxml2::XMLDeclaration* decl = doc.NewDeclaration(); doc.InsertFirstChild(decl);

tinyxml2::XMLElement* root = doc.NewElement("root"); root->SetAttribute("version", "1.0"); doc.InsertEndChild(root);

tinyxml2::XMLElement* child = doc.NewElement("item"); child->SetText("Hello, XML!"); root->InsertEndChild(child);

doc.SaveFile("output.xml"); return 0;}


2. PugiXML



PugiXML 是一个比 TinyXML-2 更快、功能更丰富的库。它支持 XPath、UTF-8/16 编码处理,并拥有便捷的 API。PugiXML 常用于需要在速度和便利性之间取得平衡的项目。它采用 MIT 许可发布。



安装

从 GitHub 下载源代码,并将 pugixml.cpp 和 pugixml.hpp 添加到项目中。要使用 XPath,请在预处理器定义中添加 PUGIXML_HAS_XPATH。



示例:使用 XPath 读取 XML

#include "pugixml.hpp"#include <iostream>

int main() { pugi::xml_document doc; doc.load_file("data.xml");

pugi::xpath_node result = doc.select_node("//item[@id='1']"); if (result) { std::cout << "Found: " << result.node().child_value() << std::endl; } return 0;}


示例:创建 XML

#include "pugixml.hpp"

int main() { pugi::xml_document doc; pugi::xml_node root = doc.append_child("configuration"); root.append_attribute("version") = "2.0";

pugi::xml_node param = root.append_child("param"); param.append_attribute("name") = "timeout"; param.text().set("30");

doc.save_file("config.xml"); return 0;}


3. RapidXML



RapidXML 是 C++ 中最快的 XML 解析库。它采用原地(in-place)工作方式(修改原始

推荐