Tinyxml2 是轻量级 c++ XML 解析库,通过包含 tinyxml2.h 和 tinyxml2.cpp 文件即可集成,使用 XMLDocument 加载文件,遍历 dom 树获取元素与属性,适合处理中小型 XML 数据。

TinyXML2 是一个轻量级、高效且易于使用的 C++ XML 解析库,适合读取和操作 XML 文件。它比原始的 TinyXML 更加现代化,内存占用更少,接口更清晰。下面介绍如何在 C++ 项目中使用 TinyXML2 来解析 XML 文件。
1. 安装与配置 TinyXML2
要使用 TinyXML2,首先需要获取并集成库文件到你的项目中:
- 下载源码:从 gitHub 仓库 https://github.com/leethomason/tinyxml2 克隆或下载源码。
- 编译并链接:将 tinyxml2.cpp 和 tinyxml2.h 添加到你的项目目录中。在大多数情况下,只需把这两个文件拖入工程即可,无需额外编译为静态库。
- 包含头文件:在源文件中使用
#include "tinyxml2.h"。
2. 基本 XML 结构示例
假设有一个名为 example.xml 的文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="1"> <title>C++ Primer</title> <author>Stanley Lippman</author> <price currency="USD">59.99</price> </book> <book id="2"> <title>Effective Modern C++</title> <author>Scott Meyers</author> <price currency="EUR">45.00</price> </book> </books>
3. 加载并解析 XML 文件
使用 TinyXML2 读取该文件并提取信息的基本代码如下:
立即学习“C++免费学习笔记(深入)”;
#include <iostream> #include "tinyxml2.h" <p>using namespace tinyxml2;</p><p>int main() { XMLDocument doc; XMLError result = doc.LoadFile("example.xml");</p><pre class='brush:php;toolbar:false;'>if (result != XML_SUCCESS) { std::cerr << "无法加载 XML 文件!错误代码:" << result << std::endl; return -1; } // 获取根元素 const XMLElement* root = doc.RootElement(); if (!root) { std::cerr << "XML 文件没有根元素!" << std::endl; return -1; } // 遍历每个 book 子元素 for (const XMLElement* bookElem = root->FirstChildElement("book"); bookElem != nullptr; bookElem = bookElem->NextSiblingElement("book")) { int id; bookElem->QueryIntAttribute("id", &id); const char* title = bookElem->FirstChildElement("title")->GetText(); const char* author = bookElem->FirstChildElement("author")->GetText(); const XMLElement* priceElem = bookElem->FirstChildElement("price"); const char* currency = priceElem->Attribute("currency"); const char* price = priceElem->GetText(); std::cout << "ID: " << id << ", 书名: " << (title ? title : "N/A") << ", 作者: " << (author ? author : "N/A") << ", 价格: " << (price ? price : "N/A") << " " << (currency ? currency : "") << std::endl; } return 0;
}
4. 关键 API 说明
- XMLDocument::LoadFile():加载 XML 文件,返回 XMLError 状态码。
- RootElement():获取文档根节点。
- FirstChildElement(tag):查找第一个指定标签名的子元素。
- NextSiblingElement(tag):遍历同级的下一个同名元素。
- Attribute(“name”):获取元素的属性值(字符串)。
- QueryIntAttribute / QueryDoubleAttribute:安全地将属性转为整型或浮点数。
- GetText():获取元素内的文本内容。
注意:所有返回的 const char* 指针由 TinyXML2 内部管理,不应手动释放,也不建议长期持有指针。
基本上就这些。TinyXML2 上手快,结构清晰,非常适合中小型项目处理 XML 配置文件或数据交换格式。只要理解了 DOM 树的遍历方式,就能灵活提取所需信息。