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

在C++中解析XML文件,常用的方法是使用第三方库来读取和操作XML数据。原生C++标准库并不支持XML解析,因此开发者通常借助像 tinyxml2、pugixml 或 Xerces-C++ 这样的库。本文以 tinyxml2 为例,介绍如何读取XML文件并使用DOM方式解析内容。
tinyxml2 是一个轻量级、易于使用的C++ XML解析库,采用DOM(Document Object Model)方式加载整个XML文档到内存中,适合处理中小型XML文件。
你可以从其 GitHub 仓库下载:https://github.com/leethomason/tinyxml2
使用方法:
立即学习“C++免费学习笔记(深入)”;
假设我们有如下XML文件(example.xml):
<?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>
下面是一个完整的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;}
注意:所有返回的字符串指针由tinyxml2内部管理,不要手动释放。如需长期保存,应复制为std::string。
基本上就这些。tinyxml2简单直观,适合大多数C++项目的XML读取需求。对于更复杂的场景(如命名空间、大文件流式处理),可考虑 pugixml 或 Xerces-C++。但对新手来说,tinyxml2是入门DOM解析的最佳选择。
以上就是c++++怎么解析XML文件_c++XML数据读取与DOM解析教程的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号