вторник, 6 апреля 2010 г.

How to serialize an object to XML by using Visual C#

Serialzation


Now here's the cool part. This is how serialization works:

ShoppingList myList = new ShoppingList();
myList.AddItem( new Item( "eggs",1.49 ) );
myList.AddItem( new Item( "ground beef",3.69 ) );
myList.AddItem( new Item( "bread",0.89 ) );


// Serialization
XmlSerializer s = new XmlSerializer( typeof( ShoppingList ) );
TextWriter w = new StreamWriter( @"c:\list.xml" );
s.Serialize( w, myList );
w.Close();

// Deserialization
ShoppingList newList;
TextReader r = new StreamReader( "list.xml" );
newList = (ShoppingList)s.Deserialize( r );
r.Close();

The first chunk of code is simply creating an instance of the ShoppingList class and populating it. After that, we have the serialization part. Here is where the object gets converted into XML. As you can see, all it requires is the use of the XmlSerializer class which is set to serialize anything of type ShoppingList (look at the constructor). The serializer does its work when the Serialize method is called and will output XML to any stream. In this case, we have it output to a file.
Next there is the deserialization part. Here we use the same serializer (since it's set to the right type) and we read in an XML file and the Deserialize method will create the appropriate ShoppingList class object. This code sample shows serialization from a file, but you could just as easily do it from an http stream.

Комментариев нет: