c++怎么解析XML文件_c++XML数据读取与DOM解析教程

使用tinyxml2库可轻松实现c++中XML文件的dom解析。首先将tinyxml2.h和cpp文件加入项目,然后通过XMLDocument加载文件,获取根节点后遍历book元素,利用Attribute和GetText方法提取id、title、author、price及currency等信息,适合处理中小型XML文件。

c++怎么解析XML文件_c++XML数据读取与DOM解析教程

在C++中解析XML文件,常用的方法是使用第三方库来读取和操作XML数据。原生C++标准库并不支持xml解析,因此开发者通常借助像 tinyxml2pugixmlXerces-C++ 这样的库。本文以 tinyxml2 为例,介绍如何读取XML文件并使用DOM方式解析内容。

1. tinyxml2 简介与安装

tinyxml2 是一个轻量级、易于使用的C++ XML解析库,采用DOM(Document Object Model)方式加载整个XML文档到内存中,适合处理中小型XML文件。

你可以从其 gitHub 仓库下载:https://github.com/leethomason/tinyxml2

使用方法:

立即学习C++免费学习笔记(深入)”;

  • 将 tinyxml2.h 和 tinyxml2.cpp 添加到你的项目中
  • 在编译时包含这两个文件即可

2. 基本XML结构示例

假设我们有如下XML文件(example.xml):

c++怎么解析XML文件_c++XML数据读取与DOM解析教程

巧文书

巧文书是一款ai写标书、AI写方案的产品。通过自研的先进AI大模型,精准解析招标文件,智能生成投标内容。

c++怎么解析XML文件_c++XML数据读取与DOM解析教程 61

查看详情 c++怎么解析XML文件_c++XML数据读取与DOM解析教程

 <?xml version="1.0" encoding="UTF-8"?> <library>   <book id="1">     <title>C++ Primer</title>     <author>Stanley Lippman</author>     <price currency="USD">59.99</price>   </book>   <book id="2">     <title>Effective C++</title>     <author>Scott Meyers</author>     <price currency="EUR">45.00</price>   </book> </library> 

3. 使用 tinyxml2 解析XML文件

下面是一个完整的C++程序,演示如何读取上述XML文件,并提取每本书的信息:

#include <iostream> #include "tinyxml2.h" <p>using namespace tinyxml2; using namespace std;</p><p>int main() { XMLDocument doc; XMLError result = doc.LoadFile("example.xml");</p><pre class='brush:php;toolbar:false;'>if (result != XML_SUCCESS) {     cout << "无法加载XML文件!错误代码:" << result << endl;     return -1; }  // 获取根节点 XMLnode* root = doc.FirstChild(); if (!root) {     cout << "根节点为空!" << endl;     return -1; }  // 遍历所有 book 子节点 for (XMLElement* book = root->FirstChildElement("book");      book != nullptr;      book = book->NextSiblingElement("book")) {      // 获取属性 id     const char* id = book->Attribute("id");      // 获取子元素文本     const char* title = book->FirstChildElement("title")->GetText();     const char* author = book->FirstChildElement("author")->GetText();      XMLElement* priceElem = book->FirstChildElement("price");     const char* price = priceElem->GetText();     const char* currency = priceElem->Attribute("currency");      cout << "ID: " << id << ", ";     cout << "书名: " << title << ", ";     cout << "作者: " << author << ", ";     cout << "价格: " << price << " " << currency << endl; }  return 0;

}

4. 关键API说明

  • XMLDocument::LoadFile():加载XML文件,返回错误码
  • FirstChildElement(“tag”):获取第一个指定标签的子元素
  • NextSiblingElement(“tag”):遍历同级的下一个同名元素
  • Attribute(“name”):获取元素的属性值
  • GetText():获取元素的文本内容

注意:所有返回的字符串指针由tinyxml2内部管理,不要手动释放。如需长期保存,应复制为std::String

基本上就这些。tinyxml2简单直观,适合大多数C++项目的XML读取需求。对于更复杂的场景(如命名空间、大文件流式处理),可考虑 pugixml 或 Xerces-C++。但对新手来说,tinyxml2是入门DOM解析的最佳选择。

上一篇
下一篇
text=ZqhQzanResources