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.
-
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.
0 comments:
Post a Comment