从Text文件中读取并将其写入XML

时间:2014-01-22 12:43:48

标签: c# asp.net xml

我想读取一个Text文件并将其写入现有的XML文件。

文本文件格式为

01 John
02 Rachel
03 Parker

我希望XML文件的输出为:

<StudentID>01<StudentID>
<StudentName>John<StudentName>
<StudentID>02<StudentID>
<StudentName>Rachel<StudentName>
<StudentID>03<StudentID>
<StudentName>Parker<StudentName>

2 个答案:

答案 0 :(得分:2)

如果您需要,这是另一种快捷方式:

将班级学生作为

class Student
{
    public string ID { get; set; }
    public string Name { get; set; }
}

然后下面的代码应该有效:

string[] lines = File.ReadAllLines("D:\\A.txt");
List<Student> list = new List<Student>();

foreach (string line in lines)
{
    string[] contents = line.Split(new char[] { ' ' });
    var student = new Student { ID = contents[0], Name = contents[1] };
    list.Add(student);
}  

using(FileStream fs = new FileStream("D:\\B.xml", FileMode.Create))
{
    new XmlSerializer(typeof(List<Student>)).Serialize(fs, list);
}

答案 1 :(得分:1)

有多种方法可以做到这一点,但我有一个旧项目的代码片段,可以帮助您入门。我改了一下来帮忙。

    public void ReadtxtFile()
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        List<string> IdList = new List<string>;
        List<string> NameList = new List<string>;

        openFileDialog1.InitialDirectory = "c:\\Users\\Person\\Desktop";
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    using (StreamReader sr = new StreamReader(openFileDialog1.OpenFile()))
                    {
                        string line;
                        // Read and display lines from the file until the end of  
                        // the file is reached. 
                        while ((line = sr.ReadLine()) != null)
                        {
                            tbResults.Text = tbResults.Text + line + Environment.NewLine;
                            int SpaceIndex = line.IndexOf("");
                            string Id = line.Substring(0, SpaceIndex);
                            string Name = line.Substring(SpaceIndex + 1, line.Length - SpaceIndex);
                           IdList.Add(Id);
                            NameList.Add(Name);
                        }
                       WriteXmlDocument(IdList, NameList);
                    }
                    myStream.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }

    private void WriteXmlDocument(List<string> IdList, List<string> NameList)
        {
//Do XML Writing here
            }
        }