(4条消息) C++解析XML文件_时·风·人的博客-CSDN博客
头文件中添加tinyxml2.h,源文件中添加tinyxml2,然后引入,也要引入fstream,方便文件操作。
#include "tinyxml2.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace tinyxml2;
void example2()
{
//声明
XMLDocument doc;
//导入xml文件
doc.LoadFile("test2.xml");
//获取根元素
XMLElement* grades = doc.RootElement();
XMLElement* surface = grades->FirstChildElement("grade");
while (surface)
{
XMLElement* surfaceChild = surface->FirstChildElement();
const char* content;
//const XMLAttribute* attributeOfSurface = surface->FirstAttribute();
//cout<< attributeOfSurface->Value() << endl;
int i = 0;//计数,方便换行
ofstream dataFile;//创建文件流
dataFile.open("dataFile.txt", ofstream::app);//打开文件
while (surfaceChild)
{
content = surfaceChild->GetText();
surfaceChild = surfaceChild->NextSiblingElement();
i++;
// 朝TXT文档中写入数据
if (i == 4) {
dataFile << content <<endl;
}
else {
dataFile << content <<",";
}
/*ofstream dataFile;
dataFile.open("dataFile.txt", ofstream::app);
dataFile << "dataFile:" << a << "\n"
<< b << endl;
dataFile.close();*/
}
// 关闭文档
dataFile.close();
surface = surface->NextSiblingElement();
}
}
然后,把需要解析的文件放在资源文件中,最好也是新建,记得encoding="gb2312"不然容易乱码
<?xml version="1.0" encoding="gb2312"?>
<grades>
<grade>
<id>2019001</id>
<name>张三</name>
<course>机器学习</course>
<score>85</score>
</grade>
<grade>
<id>2019002</id>
<name>李四</name>
<course>操作系统</course>
<score>90</score>
</grade>
<grade>
<id>2019003</id>
<name>王五</name>
<course>数据结构</course>
<score>95</score>
</grade>
</grades>
以下是一些xml解析的例子
void decodeXml()
{
//声明
XMLDocument xml;
//导入xml文件
if (xml.LoadFile("wang.xml") != XML_SUCCESS)
{
return;
}
//判断头文件是否为空
XMLElement* rootNode = xml.RootElement();
if (rootNode == NULL)
{
return;
}
//读取第一层信息
XMLElement* root_1_name = rootNode->FirstChildElement("name");
//读取第二层信息
XMLElement* root_2_gender = root_1_name->FirstChildElement("gender");
//信息输出
string text_gender = root_2_gender->GetText();
cout << "gender: "<<text_gender << endl;
//读取第一层信息
XMLElement* root_1_age = rootNode->FirstChildElement("age");
const XMLAttribute* att_1_age = root_1_age->FirstAttribute();
cout << att_1_age->Name() << ":" << att_1_age->Value() << endl;
string text_age = root_1_age->GetText();
cout << "age: " << text_age << endl;
}