Simple XmlSerializer example

This example shows how to serialize a simple object by using the XmlSerializer.

// This is the test class we want to 
// serialize:
[Serializable()]
public class TestClass
{
    private string someString;
    public string SomeString
    {
        get { return someString; }
        set { someString = value; }
    }
 
    private List<string> settings = new List<string>();
    public List<string> Settings
    {
        get { return settings; }
        set { settings = value; }
    }
 
    // These will be ignored
    [NonSerialized()]
    private int willBeIgnored1 = 1;
    private int willBeIgnored2 = 1;
 
}
 
// Example code
 
// This example requires:
// using System.Xml.Serialization;
// using System.IO;
 
// Create a new instance of the test class
TestClass TestObj = new TestClass();
 
// Set some dummy values
TestObj.SomeString = "foo";
 
TestObj.Settings.Add("A");
TestObj.Settings.Add("B");
TestObj.Settings.Add("C");
 
 
#region Save the object
 
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));
 
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, TestObj);
 
// Cleanup
WriteFileStream.Close();
 
#endregion
 
 
/*
The test.xml file will look like this:
 
<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeString>foo</SomeString>
  <Settings>
    <string>A</string>
    <string>B</string>
    <string>C</string>
  </Settings>
</TestClass>		 
*/
 
#region Load the object
 
// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
 
// Load the object saved above by using the Deserialize function
TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);
 
// Cleanup
ReadFileStream.Close();
 
#endregion
 
 
// Test the new loaded object:
MessageBox.Show(LoadedObj.SomeString);
 
foreach (string Setting in LoadedObj.Settings)
    MessageBox.Show(Setting);
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

ASas June 20, 2011 at 02:13
asdadasd
asd as June 20, 2011 at 02:11
asdasd
Derin June 06, 2011 at 04:02
Thanks. Nice work
dude April 13, 2011 at 15:01
thanks, love the simplicity
tony April 12, 2011 at 23:15
try putting a little thought into the names. makes it almost impossible to follow the code
ajanslar October 12, 2010 at 19:18
yokkkkkkkkkkaaaaadddddddm dmamdmadmamdmadadad
anicetime September 29, 2010 at 22:16
"Is this program works? What namespaces we must include?"

Try adding using:
System; using System.IO; and using System.Xml;

Generaly those are all the namespaces you require to work with xml files in C#.
Some Guy August 24, 2010 at 02:56
God these post helped alot
it-interview June 07, 2010 at 09:07
very good! please visit www.it-interview.com for more example
Clem May 28, 2010 at 21:54
This method throws "URI Streams are not supported" when instanciating the filestream.
xiaoao December 24, 2009 at 03:20
very good!
thanks a lot!
Shaun November 23, 2009 at 12:21
Hi,

Nice article, and I've tried something similar with the in-built Visual Schema Editor in VS2005, and have parsed the schema into a cs type using xsd.exe (hence being the lazy and easy way to sync the schema with class properties).

The class is of course also serializable, but I have problems attempting to write serialize the file, as it sometimes parses the xml with errors. As my program is quite intensive (writes and reads the xml between pages), I wish to ask if there is any advice you can give on preventing this problem.
Jays October 12, 2009 at 16:38
I tried doing this but it changes the datatype from int to string on one of the fields in the data collection. I was changing the data colelction to dataset then attaching it to the datagrid. When I tried sorting in the datagrid instead of asorting 1,2,11,50,1112 it becomes 1,11,1112,2,50
Solovey February 16, 2009 at 16:59
Is this program works? What namespaces we must include?