This code snippet shows you how to save / load an object using xml-serialization. It also shows you how to control you serialzation using attributes. To make this work I've made a small console based application. Please do read the comments throught the code.
using System; using System.Xml.Serialization; using System.IO;
namespace ConsoleTestApp { [Serializable] [XmlRoot("EmployeeData")] // EmployeeData will the root node name. public class Employee { [XmlAttribute] // Saves the field as an attribute in the xml file public int EmployeeID; public string Name; public string NationalId; public decimal BasicSalary; public decimal HousingAllownce; public decimal Medical; [XmlIgnore] // It ignores the field / property from being saved into XML file. As its an auto calculated field. public decimal TotalSalary { get { return (BasicSalary + HousingAllownce + Medical); } }
// For xml serialization default constructor is mandatory. public Employee() { }
public Employee(int employeeId, string name, string nationalId, decimal basicSalary, decimal housingAllownce, decimal medical) { EmployeeID = employeeId; Name = name; NationalId = nationalId; BasicSalary = basicSalary; HousingAllownce = housingAllownce; Medical = medical; }
/// /// This function serializes the object in an XML file. /// /// public static bool SerializeEmployee(Employee e, string path) { bool Flag = false; try { XmlSerializer Serializer = new XmlSerializer(typeof(Employee)); FileStream Fs = new FileStream(path, FileMode.Create); Serializer.Serialize(Fs, e); Flag = true; Fs.Dispose(); } catch { } return Flag; }
/// /// This function deserializes the object from the XML file. /// /// XML file path of serialized object. public static Employee DeSerializeEmployee(string path) { Employee ObjEmployee = null; try { FileStream Fs = new FileStream(path, FileMode.Open, FileAccess.Read); XmlSerializer DeSerializer = new XmlSerializer(typeof(Employee)); ObjEmployee = (Employee)DeSerializer.Deserialize(Fs); Fs.Dispose(); } catch {} return ObjEmployee; } }
class Program { static void Main(string[] args) { Employee ObjEmp_1 = new Employee(101, "Farhan Khan", "10176331078", 9935, 2225, 1725); bool Flag = Employee.SerializeEmployee(ObjEmp_1, @"C:\Emp.xml");
if (Flag) { Employee ObjEmp_2 = Employee.DeSerializeEmployee(@"C:\Emp.xml"); } } } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|