August 11, 2005

XML Serialization

I was just seeking for a topic to post in my blog today. I couldn’t find much. So I thought to tell you something about XMLSerialization. Most of the developers out there already know whats going on under the hood. But for the developers who’s seeking some new stuff gohead.. .net really rocks!!.

How to serialize a object to a XML file. code below.

Simply create a User class file.

[Serializable]
public class User
{
public User()
{
}

string _name;
string _age;

public string Name{get{ return _name;}set{_name = value;}}
public string Age{get{ return _age;}set{_age = value;}}

}


To serialize the user object into a xml file add the code below

public void SerializeUser()
{
//creates user object
User user = new User();
user.Name = "Ludmal";
user.Age = "25";

//this will create a xml file in the given location
TextWriter writer = new StreamWriter("C:\\user.xml");

//simply use the Serialize method from the XMLSerializer class
//
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(User));
serializer.Serialize(writer,user);
}


You can open the xml file & change the values easily.


-
Ludmal
34


To deserialize user object from the xml file simply add the below method

public User DeserializeUser()
{
//Read from the XML file
TextReader reader = new StreamReader("C:\\user.xml");

//Creates a instance of the xmlserializer class by passing the User class
XmlSerializer serializer = new XmlSerializer(typeof(User));

//Creats the user from the XmlSerializer by deserializing
User user = (User)serializer.Deserialize(r);

return user;
}

Its that simple. Try your self. We can easily save settings as XML files. Remember to add the Serializable attribute to all the classes that you want to serialize.

No comments: