The litteral answer to your question is this:
using System;
using System.Linq;
using System.Xml.Linq;
namespace XmlSerialization
{
class Program
{
static void Main(string[] args)
{
var person1 = new Person();
person1.Name = "Joe";
person1.Password = "Cla$$ified";
person1.Email = "[email protected]";
var person2 = new Person();
person2.Name = "Doe";
person2.Name = "$ecret";
person2.Email = "[email protected]";
var persons = new[] {person1, person2};
XElement xml = new XElement("persons",
from person in persons
select new XElement("person",
new XElement("name", person.Name),
new XElement("password", person.Password),
new XElement("email", person.Email))
);
xml.Save("persons.xml");
XElement restored_xml = XElement.Load("persons.xml");
Person[] restored_persons = (from person in restored_xml.Elements("person")
select new Person
{
Name = (string)person.Element("name"),
Password = (string)person.Element("password"),
Email = (string)person.Element("email")
})
.ToArray();
foreach (var person in restored_persons)
{
Console.WriteLine(person.ToString());
}
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public override string ToString()
{
return string.Format("The person with name {0} has password {1} and email {2}",
this.Name, this.Password, this.Email);
}
}
}
However, it is much better to let the built-in serializattion classes do the translation to and from XML for you. The code below needs an explicit reference to the System.Runtime.Serialization.dll. The using statement in itself is not enough:
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.Serialization;
namespace XmlSerialization
{
class Program
{
static void Main(string[] args)
{
var person1 = new Person();
person1.Name = "Joe";
person1.Password = "Cla$$ified";
person1.Email = "[email protected]";
var person2 = new Person();
person2.Name = "Doe";
person2.Name = "$ecret";
person2.Email = "[email protected]";
var persons = new[] {person1, person2};
DataContractSerializer serializer=new DataContractSerializer(typeof(Person[]));
using (var stream = new FileStream("persons.xml", FileMode.Create, FileAccess.Write))
{
serializer.WriteObject(stream,persons);
}
Person[] restored_persons;
using (var another_stream=new FileStream("persons.xml",FileMode.Open,FileAccess.Read))
{
restored_persons = serializer.ReadObject(another_stream) as Person[];
}
foreach (var person in restored_persons)
{
Console.WriteLine(person.ToString());
}
Console.ReadLine();
}
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Email { get; set; }
public override string ToString()
{
return string.Format("The person with name {0} has password {1} and email {2}",
this.Name, this.Password, this.Email);
}
}
}