Object to XML Serialization in .NET
Hi all.
Today I read a topic related to XML, Serializing and Deserializing object, I enjoyed it because it provides an awesome way to convert objects (like classes) to XML. Before today, I used for loops and tags to build XML file, which needs alot of time and takes much of work when I need to modify the XML.
In this post, I will make a simple example to introduce this issue, I’ll use C#, if you need any help in VB.NET please send to me.
I will not talk about XML, I suppose you know whats the benefits and drawbacks of XML, but I will mention two important things when you need to serialize class to XML:
- XML serialization can serialize only public data. You cannot serialize private data
- You cannot serialize object graphs; you can use XML serialization only on objects.
The following example is about Person class with some public variables, one of the is an enumerator; Gender:
To create a serilizable class you must add Serializable attribute for the class, and use an empty constructor, below is the class for Person:
[Serializable]
public class Person
{
public string Name;
public string Address;
public Gender Gender;
public DateTime RegistrationDate;
public double Mark;
{
}
}
Person person = new Person(); //Create File using FileStream
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(“~/SerializedObject.XML”),System.IO.FileMode.Create);
person.Name = “Ibrahim”;
person.Gender = Gender.Male;
person.Address = “Palestine”;
person.RegistrationDate = new DateTime(2009, 1, 1);
person.Mark = 94.5;
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Person));
fs.Close();
The output XML is like this:
The deserialization is very similar:
//Create an of Person class
Person person;�
System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(“~/SerializedObject.XML”), System.IO.FileMode.Open);
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Person));
// Use the XmlSerializer object to deserialize the data from the file
person = (Person)xs.Deserialize(fs);
fs.Close();
Tha’s all… for more details you may read this or this topic from MSDN.
Thanks for reading.
Baha' Ashour
Really cool! I like that