2014-01-22 57 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 
      } 
     } 
相關問題