Friday, 7 October 2011

c#: XML serialization and deserialization, that is from class to xml and xml to class

Consider following as xml structure



Amit
+91-9033334254
1986-01-01
Male
Single

ASI
IND
2000-01-10




  1. First you need to create class in which you can store xml data- For nested xml tag new class is created
  2. if you don't know how to create class for serialization then just search xsd.exe
    in you c:\ drive, or download from internet.
  3. Follow following command using xsd.exe in cmd
  • C:\xsd.exe Employee.xml
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\Employee.xsd'.
  • Above Command give u xml schema, later this schema will create class
  • C:\xsd.exe Employee.xsd /classes
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\Employee.cs'.
The Above code will generate required classes automatically,
it may contain three class, Employee, Employee_info, Branch etc
but really we don't need to care about these classes.
let's come to the actual coding


// Creating Object of XML Serializer for Getting Data into Emplyee Object
XmlSerializer objXmlSerializer = new XmlSerializer(typeof(Employees));
TextReader objTextReader;
Stream objStream = null;
FileStream objFileStream = null;

// Generated class from xsd.exe
Employees objEmployees = null;

objFileStream = new FileStream("Employee.xml", FileMode.OpenOrCreate);
objTextReader = new StreamReader(objFileStream);

// Get the xml data into the objEmployees obj
objEmployees = (Employees)objXmlSerializer.Deserialize(objTextReader);
objFileStream.Close();

///
/// Display Employees Records on Console
///

public void DisplayEmployeeInfo(Employees Employee)
{
if (Employee == null )
{
Console.WriteLine(Defination.NoRecordFound);
return;
}

for (int nIndex = 0; nIndex < Employee.Length; nIndex++)
{
// Calculating emp age
TimeSpan objTimeSpan = DateTime.Now - DateTime.Parse(Employee[nIndex].BirthDate);

Console.Write("{0}\t{1}\t{2} {3} ", Employee[nIndex].Name, Employee[nIndex].Telephone, ((int)objTimeSpan.TotalDays / 365), Employee[nIndex].RelationshipStatus);

Console.Write("\t{0}\t{1}\t{2}", Employee[nIndex].Branch[0].Name, Employee[nIndex].Branch[0].CountryCode, Employee[nIndex].Branch[0].EstablishmentDate);
Console.WriteLine();
}
}

// for insert / update just take new emplyees obj and serialize it
Employees objNewEmployees = new Employees();

// fill the required info like u get it in Display() method
...
...
XmlSerializer serializer = new XmlSerializer(typeof(Employees));
TextWriter textWriter = new StreamWriter("New file.xml");
serializer.Serialize(textWriter, objNewEmployees);
textWriter.Close();

0 comments:

Post a Comment