Serialize and deserialize objects to an XML file

This code shows the simplest way to automatically convert the information in an object to an XML file and back into an object. This is useful if you need to make information available web-server like on your server for other applications to pick it up. I just cut the significant parts out of Visual Studio so you'll have to build it into whatever form you like. Make sure you have write permissions on the directory.

from the .aspx file

       //serialize
       private void Button3_Click(object sender, System.EventArgs e)
       {
           Book b = new Book();
           b.Title = "Windows Forms";
           b.Isbn = "728372837";

           XmlSerializer serializer = new XmlSerializer(typeof(Book));
           TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));
           serializer.Serialize(tw,b);
           tw.Close();
       }


       //deserialize
       private void Button4_Click(object sender, System.EventArgs e)
       {
           XmlSerializer serializer = new XmlSerializer(typeof(Book));
           TextReader tr = new StreamReader(Server.MapPath("book1.xml"));
           Book b = (Book)serializer.Deserialize(tr);
           tr.Close();

           Title.Text = b.Title;
           Isbn.Text = b.Isbn;
           
       }

Book.cs

using System;

namespace Serialize
{
   public class Book
   {
       public string Title;
       public string Isbn;
   }
}

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer lets you make more mistakes faster than any other invention in human history, with the possible exceptions of handguns and tequila” - Mitch Ratcliffe