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

在C++项目中处理XML文件时,TinyXML-2是一个轻量级、易用且高效的开源库。它提供简洁的API来读取、修改和生成XML数据,非常适合中小型项目。下面介绍如何集成并使用TinyXML-2解析XML文件。
要使用TinyXML-2,首先需要获取源码并将其加入项目:
如果使用CMake,可以这样添加:
add_executable(myapp main.cpp tinyxml2.cpp) target_include_directories(myapp PRIVATE .)
使用TinyXML-2读取XML文件非常简单。核心类是tinyxml2::XMLDocument,用于加载和表示整个XML文档。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include "tinyxml2.h"
#include <iostream>
<p>using namespace tinyxml2;</p><p>int main() {
XMLDocument doc;
XMLError result = doc.LoadFile("config.xml");
if (result != XML_SUCCESS) {
std::cout << "无法加载XML文件" << std::endl;
return -1;
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 获取根元素
XMLElement* root = doc.FirstChildElement();
if (!root) {
std::cout << "XML文件为空" << std::endl;
return -1;
}
std::cout << "根元素: " << root->Name() << std::endl;}
解析XML通常需要访问子元素、文本内容和属性值。TinyXML-2提供了清晰的层级访问方式。
假设有一个如下结构的XML文件:
<?xml version="1.0"?>
<settings>
<window width="800" height="600" fullscreen="false">主窗口</window>
<user name="Tom" age="25"/>
</settings>读取这些数据的代码:
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");
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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 << "用户: " << name << ", 年龄: " << age << std::endl; }
TinyXML-2也支持创建新的XML文档并保存到文件。
示例:生成上述结构的XML:
XMLDocument newDoc;
<p>// 添加声明
XMLDeclaration* decl = newDoc.NewDeclaration();
newDoc.InsertFirstChild(decl);</p><p>// 创建根节点
XMLElement* root = newDoc.NewElement("settings");
newDoc.InsertEndChild(root);</p><p>// 添加window元素
XMLElement* window = newDoc.NewElement("window");
window->SetAttribute("width", 1024);
window->SetAttribute("height", 768);
window->SetAttribute("fullscreen", true);
window->SetText("新窗口");
root->InsertEndChild(window);</p><p>// 添加user元素
XMLElement* user = newDoc.NewElement("user");
user->SetAttribute("name", "Jerry");
user->SetAttribute("age", 30);
root->InsertEndChild(user);</p><p>// 保存到文件
XMLError result = newDoc.SaveFile("output.xml");
if (result != XML_SUCCESS) {
std::cout << "保存失败" << std::endl;
}基本上就这些。TinyXML-2上手快,不需要复杂配置,适合快速实现XML读写功能。注意检查指针是否为空,避免因XML结构不匹配导致崩溃。不复杂但容易忽略。
以上就是C++如何解析xml文件 TinyXML-2开源库的集成与使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号