Monday, October 27, 2008

How to serialize an object to/from xml

I copied the below almost entirely from this page but didn't want to risk it going away before I had it committed to memory, so read that page not mine! I am not sure why you just wouldn't create a method on the object to do that but all the examples I have seen use a separate void class.

static public void SerializeToXML(Movie movie)
XmlSerializer serializer = new XmlSerializer(typeof(Movie));
TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
serializer.Serialize(textWriter, movie);

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);

return movies;

No comments: