tinystr头文件需要去下载
https://sourceforge.net/projects/tinyxml/
在vs中导入.cpp和.h文件,记得把文件复制一份放到cpp所在文件夹,不然无法运行
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "tinystr.h"
#include "tinyxml.h"
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <sstream>
using namespace std;
typedef struct course
{
string cname;
string grade;
}course;
typedef struct students
{
string id;
string name;
vector<course> cs;
}students;
void CreateXmlFile(const char* path, map<string, students> mp)
{
//创建一个XML的文档对象。
TiXmlDocument myDocument;
//添加一个xml头
TiXmlDeclaration* pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
myDocument.LinkEndChild(pDeclaration);
//创建一个根元素并连接。
TiXmlElement* RootElement = new TiXmlElement("students");
myDocument.LinkEndChild(RootElement);
TiXmlElement* PersonElement;
map<string, students>::iterator it;
it = mp.begin();
while (it != mp.end())
{
//创建一个Person元素并连接。
PersonElement = new TiXmlElement("student");
//设置Person元素的属性。
//PersonElement->SetAttribute("ID", "1");
//创建id元素、name元素并连接。
TiXmlElement* IdElement = new TiXmlElement("学号");
TiXmlElement* NameElement = new TiXmlElement("姓名");
PersonElement->LinkEndChild(IdElement);
PersonElement->LinkEndChild(NameElement);
//设置name元素和age元素的内容并连接。
TiXmlText* IdContent = new TiXmlText(it->first.c_str());
TiXmlText* NameContent = new TiXmlText(it->second.name.c_str());
IdElement->LinkEndChild(IdContent);
NameElement->LinkEndChild(NameContent);
for (int i = 0; i < it->second.cs.size(); i++)
{
//创建course元素并连接。
TiXmlElement* courseElement = new TiXmlElement("课程");
PersonElement->LinkEndChild(courseElement);
courseElement->SetAttribute("课程名", it->second.cs[i].cname.c_str());
//设置course元素内容并连接。
TiXmlText* gradeContent = new TiXmlText(it->second.cs[i].grade.c_str());
courseElement->LinkEndChild(gradeContent);
}
RootElement->LinkEndChild(PersonElement);
it++;
}
myDocument.SaveFile(path);//保存到文件
}
int main(void)
{
vector<string> str;
string s;
string fileName;
cout << "请输入文件名:" << endl;
cin >> fileName;
ifstream infile(fileName.c_str());
while (getline(infile, s))
{
str.push_back(s);
}
map<string, students> mp;
int i, j, k;
for (k = 0; k < str.size(); k++)
{
i = 0, j = 0;
vector<string> temp;
while (str[k][j] != 0)
{
j = i;
while (str[k][j] != 0 && str[k][j] != ',') j++;
temp.push_back(str[k].substr(i, j - i));
i = j + 1;
}
students stu;
stu.id = temp[0];
stu.name = temp[1];
course cs0;
cs0.cname = temp[2];
cs0.grade = temp[3];
if (mp.count(temp[0]) > 0) {
mp.find(temp[0])->second.cs.push_back(cs0);
}
else
{
stu.cs.push_back(cs0);
mp.insert(pair<string, students>(temp[0], stu));
}
}
const char* path = "D:/研究生复试李泽平/xml/txt-xml/student.xml";
CreateXmlFile(path, mp);
cout << " ";
system("pause");
return 0;
}