2014-01-22 7 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

Обратите внимание, что выход не является " valid 'xml, поскольку он имеет несколько корневых узлов. Поэтому сериализация не является вариантом. – Aphelion

+0

@MauriceStam false, сериализация IEnumerable даст вам несколько корней. – Gusdor

+0

@Gusdor не приведет к созданию корневой таблицы, представляющей тип коллекции? Если нет, спасибо, что рассказали мне :) – Aphelion

ответ

2

Вот еще один быстрый способ, если вам нужно:

Имея класс Student, как

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 
      } 
     } 
Смежные вопросы