C++如何操作XML文件_使用TinyXML2库解析和生成C++ XML数据

TinyXML-2是C++中轻量级XML操作库,支持解析与生成XML文件。1. 通过包含tinyxml2.h/cpp文件或CMake引入库;2. 使用XMLDocument加载文件并读取元素属性和文本内容;3. 可创建XML结构并保存到文件;4. 提供安全读取、遍历子元素等常用操作技巧,适用于中小型项目。

在C++中操作XML文件,TinyXML-2是一个轻量、易用且高效的库。它允许你解析已有的XML文件,也可以创建新的XML数据并保存到文件。下面介绍如何使用TinyXML-2进行XML的读取与生成。

1. 安装与配置 TinyXML-2

TinyXML-2 是一个只有头文件和源文件的小型库,无需复杂安装。你可以从其 GitHub 仓库获取:

  • 下载地址:https://github.com/leethomason/tinyxml2
  • 将 tinyxml2.h 和 tinyxml2.cpp 添加到你的项目中
  • 编译时确保包含 tinyxml2.cpp 源文件

如果你使用的是 CMake,可以这样引入:

find_package(Git QUIET)
include(FetchContent)
FetchContent_Declare(
  tinyxml2
  GIT_REPOSITORY https://github.com/leethomason/tinyxml2.git
  GIT_TAG        master
)
FetchContent_MakeAvailable(tinyxml2)
target_link_libraries(your_target_name PRIVATE tinyxml2)

2. 解析 XML 文件

假设有一个名为 config.xml 的文件:



    
        My Game
    
    

使用 TinyXML-2 读取该文件并提取数据:

#include "tinyxml2.h"
#include 
using namespace tinyxml2;

void readXML() { XMLDocument doc; XMLError result = doc.LoadFile("config.xml"); if (result != XML_SUCCESS) { std::cerr << "Failed to load file: " << result << std::endl; return; }

// 获取根节点
const XMLElement* config = doc.FirstChildElement("config");
if (!config) return;

// 读取 window 元素属性
const XMLElement* window = config->FirstChildElement("window");
if (window) {
    int width = 0, height = 0;
    window->QueryIntAttribute("width", &width);
    window->QueryIntAttribute("height", &height);
    const char* title = window->FirstChildElement("title")->GetText();

    std::cout << "Window: " << width << "x" << height 
              << ", Title: " << title << std::endl;
}

// 读取 fullscreen 属性
const XMLElement* fs = config->FirstChildElement("fullscreen");
if (fs) {
    bool value = false;
    fs->QueryBoolAttribute("value", &value);
    std::cout << "Fullscreen: " << (value ? "true" : "false") << std::endl;
}

}

3. 创建并生成 XML 文件

你可以使用 TinyXML-2 构建 XML 结构并写入文件:

void writeXML() {
    XMLDocument doc;
// 声明
XMLDeclaration* decl = doc.NewDeclaration();
doc.InsertFirstChild(decl);

// 根元素
XMLElement* config = doc.NewElement("config");
doc.InsertEndChild(config);

// 添加 window 子元素
XMLElement* window = doc.NewElement("window");
window->SetAttribute("width", 1024);
window->SetAttribute("height", 768);
config->InsertEndChild(window);

XMLElement* title = doc.NewElement("title");
title->SetText("New Game");
window->InsertEndChild(title);

// 添加 fullscreen 元素
XMLElement* fs = doc.NewElement("fullscreen");
fs->SetAttribute("value", true);
config->InsertEndChild(fs);

// 保存到文件
XMLError result = doc.SaveFile("output.xml");
if (result != XML_SUCCESS) {
    std::cerr << "Failed to save file." << std::endl;
} else {
    std::cout << "XML file saved successfully." << std::endl;
}

}

运行后会生成 output.xml,内容如下:



    
        New Game
    
    

4. 常见操作技巧

  • 检查元素是否存在:始终判断指针是否为 nullptr,避免崩溃
  • 安全读取属性:使用 QueryIntAttribute、QueryBoolAttribute 等返回 XMLError,可判断是否成功读取
  • 文本内容处理:使用 GetText() 获取元素内的文本,注意空值判断
  • 遍历子元素:使用 NextSiblingElement() 循环遍历同名节点

示例:遍历所有 item 节点

const XMLElement* item = config->FirstChildElement("item");
while (item) {
    const char* name = item->Attribute("name");
    std::cout << "Item: " << name << std::endl;
    item = item->NextSiblingElement("item");
}

基本上就这些。TinyXML-2 虽然功能不如大型库全面,但对大多数中小型项目已经足够,接口清晰,易于集成。只要掌握基本的节点查找、属性读取和元素创建,就能高效完成 XML 数据操作。