Sample Downloads C# version: http://code.msdn.microsoft.com/CSXmlSerialization-6150d4bf VB version: http://code.msdn.microsoft.com/VBXmlSerialization-5492ab29
Today’s code sample demonstrates how to serialize an in-memory object to a local xml file and how to deserialize the xml file back to an in-memory object using VC# and VB.NET.
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.
This sample shows how to serialize an in-memory object to a local xml file and how to deserialize the xml file back to an in-memory object using VC# and VB.NET. The designed MySerializableType includes int, string, generic, as well as customized type field and property.
1. We define a MySerializableType whose instance will be serialized to xml file. The MySerializableType includes int, string, bool, generic List and a customized type field/property. Mark the type as [Serializable()].
2. We define a AnotherType which is used for MySerializableType's inner customized type. Mark the type as [Serializable()].
3. In the main method, the codes firstly create and initialize an object of MySerializableType.
4. Then it creates a XmlSerializer and StreamWriter to serialize the instance to local driver as XML file.
The generated xml file in step4 looks like:
<?xml version="1.0" encoding="utf-8" ?>
- <MySerializableType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<StringValue>Inner Test String</StringValue>
<string>List Item 1</string>
<string>List Item 2</string>
<string>List Item 3</string>
5. Then it creates a StreamReader to read and deserialize the xml file back to object instance.