C++实现对XML文件的读写操作
发布日期:2021-05-10 23:21:19 浏览次数:28 分类:精选文章

本文共 3096 字,大约阅读时间需要 10 分钟。

预先准备

操作系统:建议使用 Win10(UNIX 环境也可按此操作)

编译器:使用 gcc/g++

软件编辑器:Visual Studio Code

依赖文件:完整的依赖文件请参考官方文档安装配置

注意:读者需事先安装配置 gcc/g++,具体细节可参考安装指南。


使用方法

新建项目文件夹(例如:test),将 tinyXml 解压后,将以下6个文件复制到项目文件夹中。

文件列表:

  • tinyxml.h
  • TiXmlDocument.h
  • TiXmlDeclaration.h
  • TiXml Comment.h
  • TiXmlElement.h
  • TiXmlAttribute.h

使用 Visual Studio Code 打开项目文件夹,新建 test.cpp 文件,将以下代码粘贴至 test.cpp 文件中。

代码示例:

#include 
#include "tinyxml.h"
#include
#include
using namespace std;
// 创建 XML 文件
int writeXmlFile() {
TiXmlDocument *writeDoc = new TiXmlDocument;
// 声明部分
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "UTF-8", "yes");
writeDoc->LinkEndChild(decl);
int n = 3;
TiXmlElement *RootElement = new TiXmlElement("Info");
RootElement->SetAttribute("num", n);
writeDoc->LinkEndChild(RootElement);
for (int i = 0; i < n; ++i) {
create stu element
TiXmlElement *stuElement = new TiXmlElement("stu");
stuElement->SetAttribute("class", "A");
if (i == 2) {
stuElement->SetAttribute("class", "B");
}
stuElement->SetAttribute("id", i + 1);
stuElement->SetAttribute("flag", (i + 1) * 10);
RootElement->LinkEndChild(stuElement);
// 姓名
TiXmlElement *nameElement = new TiXmlElement("name");
stuElement->LinkEndChild(nameElement);
TiXmlText *nameContent = new TiXmlText("mike");
nameElement->LinkEndChild(nameContent);
// 分数
TiXmlElement *scoreElement = new TiXmlElement("score");
stuElement->LinkEndChild(scoreElement);
TiXmlText *scoreContent = new TiXmlText("88");
scoreElement->LinkEndChild(scoreContent);
// 城市
TiXmlElement *cityElement = new TiXmlElement("city");
stuElement->LinkEndChild(cityElement);
TiXmlText *cityContent = new TiXmlText("Shenzhen");
cityElement->LinkEndChild(cityContent);
}
writeDoc->SaveFile("stu_info.xml");
delete writeDoc;
return 1;
}
// 解析 XML 文件
int readXmlFile() {
TiXmlDocument myDoc("stu_info.xml");
bool loadOk = myDoc.LoadFile();
if (!loadOk) {
cout << "Could not load the test file. Error:" << myDoc.ErrorMessage() << endl;
exit(1);
}
// 获取根元素
TiXmlElement *rootElement = myDoc.RootElement();
cout << "[root name]" << rootElement->Value() << endl;
// 遍历子节点
TiXmlElement *pEle = rootElement;
TiXmlElement *stuElement = pEle->FirstChildElement();
while (stuElement != NULL) {
cout << stuElement->Value() << " ";
// 输出属性
TiXmlAttribute *pAttr = stuElement->FirstAttribute();
while (pAttr != NULL) {
cout << pAttr->Name() << ":" << pAttr->Value() << " ";
pAttr = pAttr->Next();
}
// 获取子元素
stuElement = stuElement->NextSiblingElement();
pEle = stuElement->FirstChildElement();
}
return 1;
}

编译运行

单击 test.cpp 文件右键选择“在终端中打开”,输入以下命令:

g++ *.cpp

或(如果使用 gcc):

gcc *.cpp

生成可执行文件 a.exe 后,输入以下命令运行:

./a

完成!

上一篇:Ajax学习小结
下一篇:JSP知识点概述

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月28日 04时37分56秒