針對您的問題的litteral回答是這樣的:
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);
}
}
}
但是,更好的讓內置serializattion類做翻譯和XML爲您服務。下面的代碼需要顯式引用System.Runtime.Serialization.dll。使用聲明本身是不夠的:
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);
}
}
}
請注意,使用元素來描述位置(「person1」,「person2」)是一個非常糟糕的主意......屬性會好得多。 – 2009-10-06 05:16:52