- 被序列化的对象必须是public访问权限,
- 对象不能包含Hashtable,
- 如果将对象的构造函数重载,必须包含默认的构造函数,即public constructor(){}
- 对于list操作如下:
public class Movie
{
public string Title
{ get; set; }
public int Rating
{ get; set; }
public DateTime ReleaseDate
{ get; set; }
}
static public void SerializeToXML(List<Movie> movies)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Movie>));
TextWriter textWriter = new StreamWriter(@"C:/movie.xml");
serializer.Serialize(textWriter, movies);
textWriter.Close();
}
static List<Movie> DeserializeFromXML()
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
TextReader textReader = new StreamReader(@"C:/movie.xml");
List<Movie> movies;
movies = (List<Movie>)deserializer.Deserialize(textReader);
textReader.Close();
return movies;
}
static void Main(string[] args)
{
Movie movie = new Movie();
movie.Title = "Starship Troopers";
movie.ReleaseDate = DateTime.Parse("11/7/1997");
movie.Rating = 6.9f;
Movie movie2 = new Movie();
movie2.Title = "Ace Ventura: When Nature Calls";
movie2.ReleaseDate = DateTime.Parse("11/10/1995");
movie2.Rating = 5.4f;
List<Movie> movies = new List<Movie>() { movie, movie2 };
SerializeToXML(movies);
}