Monday, 23 February 2015

C# XML Serialization and Deserialization

1.Create a Asp.Net web application.
2.Add a web page.
3.Add new xml file.
<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car>
</Cars>
</CarCollection>
Add above code in xml.
Now generate methods and properties for xml file using XML Schema Definition Tool (Xsd.exe)
Now open Visual Studio Command Prompt 2010 Administration mode.
Type xsd
you should get all help..
Generate the xsd file from xml, using below command.
C:\WINDOWS\system32>xsd C:\Users\Admin\Documents\Test\MyCars.xml
Generate the C# class file using below command.
C:\WINDOWS\system32>xsd C:\Users\Admin\Documents\Test\MyCars.xsd /c /out:C:\Users\Admin\Documents\Test
You will get MyCars.cs file under C:\Users\Admin\Documents\Test
Add MyCars.cs to your solution.
Build..should be no errors
In the webpage add button under button click write below code..
protected void btnCar_Click(object sender, EventArgs e)
{
CarCollection cars = null;
string path = "C:\\Users\\Admin\\Documents\\Visual Studio 2013\\Projects\\Testxml\\Testxml\\MyCars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
string strModel = cars.Items[0].Car[0].Model;
//You can read all properties....using for loop
//Start
CarCollection myCars = null;
using (XmlReader myReader = XmlReader.Create(path))
{
myCars = (CarCollection)serializer.Deserialize(myReader);
}
//End
}

Full code.....