首先集成TinyXML-2库,将tinyxml2.h和cpp加入项目;再用XMLDocument加载文件,通过XMLElement遍历节点与属性;支持创建新文档并保存。

在C++项目中处理XML文件时,TinyXML-2是一个轻量级、易用且高效的开源库。它提供简洁的API来读取、修改和生成XML数据,非常适合中小型项目。下面介绍如何集成并使用TinyXML-2解析XML文件。
集成TinyXML-2到C++项目
要使用TinyXML-2,首先需要获取源码并将其加入项目:
- 从GitHub下载TinyXML-2源码:https://www.php.cn/link/9044514567a4b7df8fe3db93c06d66ee
- 将 tinyxml2.h 和 tinyxml2.cpp 文件复制到你的项目目录
- 在项目中包含这两个文件,并确保编译器能正常编译tinyxml2.cpp
如果使用CMake,可以这样添加:
add_executable(myapp main.cpp tinyxml2.cpp) target_include_directories(myapp PRIVATE .)
加载和解析XML文件
使用TinyXML-2读取XML文件非常简单。核心类是tinyxml2::XMLDocument,用于加载和表示整个XML文档。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include "tinyxml2.h" #includeusing namespace tinyxml2;
int main() { XMLDocument doc; XMLError result = doc.LoadFile("config.xml"); if (result != XML_SUCCESS) { std::cout << "无法加载XML文件" << std::endl; return -1; }
// 获取根元素 XMLElement* root = doc.FirstChildElement(); if (!root) { std::cout << "XML文件为空" << std::endl; return -1; } std::cout << "根元素: " << root->Name() << std::endl;}
遍历和读取元素与属性
解析XML通常需要访问子元素、文本内容和属性值。TinyXML-2提供了清晰的层级访问方式。
假设有一个如下结构的XML文件:
主窗口 读取这些数据的代码:
XMLElement* window = root->FirstChildElement("window"); if (window) { const char* text = window->GetText(); // 获取文本内容:"主窗口" int width = window->IntAttribute("width"); // 获取整数属性 int height = window->IntAttribute("height"); bool fullscreen = window->BoolAttribute("fullscreen");std::cout << "窗口: " << text << ", " << width << "x" << height << ", 全屏: " << (fullscreen ? "是" : "否") << std::endl;}
XMLElement user = root->FirstChildElement("user"); if (user) { const char name = user->Attribute("name"); int age = user->IntAttribute("age"); std::cout
创建和保存XML文件
TinyXML-2也支持创建新的XML文档并保存到文件。
示例:生成上述结构的XML:
XMLDocument newDoc;// 添加声明 XMLDeclaration* decl = newDoc.NewDeclaration(); newDoc.InsertFirstChild(decl);
// 创建根节点 XMLElement* root = newDoc.NewElement("settings"); newDoc.InsertEndChild(root);
// 添加window元素 XMLElement* window = newDoc.NewElement("window"); window->SetAttribute("width", 1024); window->SetAttribute("height", 768); window->SetAttribute("fullscreen", true); window->SetText("新窗口"); root->InsertEndChild(window);
// 添加user元素 XMLElement* user = newDoc.NewElement("user"); user->SetAttribute("name", "Jerry"); user->SetAttribute("age", 30); root->InsertEndChild(user);
// 保存到文件 XMLError result = newDoc.SaveFile("output.xml"); if (result != XML_SUCCESS) { std::cout << "保存失败" << std::endl; }
基本上就这些。TinyXML-2上手快,不需要复杂配置,适合快速实现XML读写功能。注意检查指针是否为空,避免因XML结构不匹配导致崩溃。不复杂但容易忽略。










