我的复杂实现
program.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace c2018
{
internal class Program
{
static void Main(string[] args)
{
string inputFile = "D:/DDD/2018.txt";
string outputFile = "D:/DDD/2018.xml";
// 读取txt文件
string[] lines = File.ReadAllLines(inputFile);
// 创建XmlDocument对象并添加根元素
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("students");
doc.AppendChild(root);
List<student> students = new List<student>();
foreach(string line in lines)
{
string[] fields = line.Split(',');
if (students.Any(e => e.id == int.Parse(fields[0])))
{
students.Find(e=>e.id == int.Parse(fields[0])).myDictionary.Add(fields[2],int.Parse(fields[3]));
}
else
{
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add(fields[2], int.Parse(fields[3]));
student student1 = new student(int.Parse(fields[0]), fields[1],myDictionary);
students.Add(student1);
}
}
// 遍历每一行,将其添加为xml元素
foreach (student student in students)
{
XmlElement row = doc.CreateElement("student");
XmlElement field1 = doc.CreateElement("学号");
field1.InnerText = student.id.ToString();
row.AppendChild(field1);
XmlElement field2 = doc.CreateElement("姓名");
field2.InnerText = student.name;
row.AppendChild(field2);
foreach(var item in student.myDictionary)
{
XmlElement field3 = doc.CreateElement(item.Key);
field3.InnerText = item.Value.ToString();
row.AppendChild(field3);
}
root.AppendChild(row);
}
// 将xml文档保存到文件
doc.Save(outputFile);
Console.WriteLine($"Successfully converted {inputFile} to {outputFile}.");
Console.ReadLine();
}
}
}
student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace c2018
{
internal class student
{
public int id;
public string name;
public string course;
public int score;
public Dictionary<string, int> myDictionary = new Dictionary<string, int>();
public student(int id, string name, Dictionary<string,int>a)
{
this.id = id;
this.name = name;
myDictionary = a;
}
}
}