如何使用c#将来自txt文件的数据存储在XML文件中?

时间:2016-05-17 04:59:14

标签: c# xml

我使用分隔符将用户的数据存储在文本文件中,这是我的代码

function myConstructor(a,b,c){
    this.a = a;
    this.b = b;
    this.c = c;
}

var newObject = new myConstructor(1,2,3);   // {a: 1, b: 2, c: 3}

var myArguments = [1,2,3];
var anotherObject = new function(){
    return myConstructor.apply(this,myArguments);
  }; // {a: 1, b: 2, c: 3}

这就是问题,在我将数据存储在文本文件中之后,我想将它保存在XML文件中,如#34;在图片中#34;。

enter image description here

我试过但我在这张照片中失败了

enter image description here

这是我在seconde图片中制作的代码

Student std = new Student();
dataGridView1.Rows.Clear(); //to clear the dataGridView Before showing the data
dataGridView1.Refresh();
List<Student> students = new List<Student>();
using (StreamReader sr = new StreamReader(txt_path.Text))
{
    int x = 0;
    while (sr.Peek() >= 0)
    {
        string str;
        string[] strArray;
        str = sr.ReadLine();

        strArray = str.Split('@', '#');
        Student s = new Student();
        s.ID = int.Parse(strArray[0]);
        s.Name = strArray[1];
        s.Address = strArray[2];
        s.Phone = strArray[3];

        DataGridViewRow row = new DataGridViewRow();
        row.CreateCells(dataGridView1);  // this line was missing
        row.Cells[x].Value = s.ID;
        row.Cells[++x].Value = s.Name;
        row.Cells[++x].Value = s.Address;
        row.Cells[++x].Value = s.Phone;

        dataGridView1.Rows.Add(row);
        students.Add(s);
        x = 0;
    }
}

text file

1 个答案:

答案 0 :(得分:0)

有点不清楚,看着你的代码我假设你想要阅读一个文本文件并生成一个Xml文件。

你可以这样做。

var students = File.ReadLines(txt_path.Text)
    .Select(line=>line.Split('@', '#')
    .Select(x=> new Student()
                {
                    ID = int.Parse(x[0]),
                    Name = x[1],
                    Address = x[2],
                    Phone = x[3]
                }) 
    .ToList();

获得学生列表后,您可以使用LinqXml并创建xml文件。

XElement element = 
    new XElement("Students",
        (from student in students 
             select new XElement("Student",
                 new XElement("ID", student.ID),
                 new XElement("Name",student.Name),
                 new XElement("Address", student.Address),
                 new XElement("Phone",student.Phone)
             )
         )
     ); 

 element.Save(outputfile);  

最后但并非最不重要的是,您可以使用List<Student>作为DataGridView的绑定来源。

dataGridView1.DataSource new BindingSource(new BindingList<Student>(students);

选中此demo,您将了解其工作原理。