Cenk Tigan Cenk Tigan - 5 days ago 5
C# Question

Howto read file into collection string to create a xml in C#

frist i want to read and store informations about persons from simple txt files.

files look like this e.g.

person=3
name=Tigan
sirname=Cenk
id=1231
nationality=whatever
name2=Joo
sirname2=Boo
id2=1299
nationality2=whatever
name3=Joo
sirname3=Boo
id3=1211
nationality3=whatever


i create a person class like the following exapmle:

class Person
{
public string name { get; set; }
public string sirname { get; set; }
public int id { get; set; }
public string nationality { get; set; }
}


then the following code to read the lines from the files:

List<string> lines = File.ReadAllLines(Path2File).ToList();
List<Person> list = new List<Person>();


after that i split the lines with the delimeter "="

foreach (var line in lines)
{
Char delimiter = '=';
string[] contents = line.Split(delimiter);
}


Now my question is, how can i past contents"[1]"(e.g.Tigan) to the right place on my collection array contetns"[0]" (e.g.name or name1) to person.name

i need to return list with all the data to use it for creating a xml.

i hope someone can help me.

kind regards.

Answer

I would go for something like this:

var person = new Person();
foreach (var line in lines)
   {
   Char delimiter = '=';
   string[] contents = line.Split(delimiter);
   switch(contents[0])       
      {         
         case "person":  
            if(person.id != Convert.ToInt32(contents[1]))
               {
                   list.Add(person);
                   person = new Person();
               }
            person.id = Convert.ToInt32(contents[1]);
            break;  
         case "name ":   
            person.name = contents[1];
            break;  
         case "sirname":            
            person.sirname = contents[1];
            break; 
        //...etc
       }
   }
Comments