Serializing Objects to XML with C# and .NET
Posted: (EET/GMT+2)
Serializing Objects to XML with C# and .NET
Jun 22, 2002
Microsoft Visual Studio .NET
Every object in .NET has a ToString method that converts the object's internal data to a string. This is great for stream or sending the object over a wire, but sometimes you need more. That is when XML serialization comes into play.
XML serialization means that you wish to convert an object to a string-based format, but one that is valid XML. In .NET, this is quite easy to achieve with a bit help from a XmlSerializer class. This class takes any object and tries to convert it to XML. It is able to list public properties, fields and just about anything.
If you are using the C# language and Visual Studio .NET, you can simply use the following code to convert an object (here, are simple integer value) to XML. The example application is a Windows Forms application that contains a button and a memo field.
The code goes like this:
private void button1_Click(object sender, System.EventArgs e)
{
int myInt = 32;
XmlSerializer mySerializer = new XmlSerializer(typeof(int));
StringWriter myStringWriter = new StringWriter();
mySerializer.Serialize(myStringWriter,myInt);
textBox1.Text = myInt.ToString()+"\r\n\r\n"+
myStringWriter.ToString();
}
Here, the two special classes needed are XmlSerializer and StringWriter. These are found in the namespaces System.Xml.Serialization and System.IO respectively, so you need to have the following "using" clauses in your C# code:
using System.Xml.Serialization; using System.IO;
When run, the application looks like this on the screen:

You probably cannot read the output easily from the screenshot, so we've copied the output here:
32 <?xml version="1.0" encoding="utf-16"?> <int>32</int>
As you can see, there is a difference in the output of the ToString method and using the XmlSerializer class. And did XML serialization require much effort? We feel that the answer is no.
Download the example code
Download serializingobjectstoxmlwithcsharp.zip (9 kB) which contains the sample application presented in this article. Please note that the sample application will require Visual Studio .NET to be installed to compile.
* * *
Do you need consulting help to get your .NET project started? Contact us today!