2014-01-22 156 views
1

我想读取一个文本文件并将其写入现有XML文件。从文本文件读取并将其写入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> 
+0

注意,输出不“有效的'xml,因为它有多个根节点。因此,序列化是没有选择的。 – Aphelion

+0

@MauriceStam false,序列化IEnumerable 会给你多个根。 – Gusdor

+0

@Gusdor会不会导致表示集合类型的根注释?如果没有,谢谢你告诉我:) – Aphelion

回答

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); 
} 
+0

谢谢你,先生!正是我想要的。 – Khan

+0

不客气) –

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 
      } 
     } 
相关问题