How to use XmlSerializer in C#?


Serialization/ De-serialization allow communication with another application by sending and receiving data. With XmlSerializer, you can control how objects are encoded into XML.

To perform XML Serialization, you need the following two classes −

  • StreamWriter class
  • XmlSerializer class

Call the Serialize method with the parameters of the StreamWriter and object to serialize.

string myPath = "new.xml";
XmlSerializer s = new XmlSerializer(settings.GetType());
StreamWriter streamWriter = new StreamWriter(myPath);
s.Serialize(streamWriter, settings);    

An XML file is visible with the name “new.xml”.

Now to deserialize.

MySettings mySettings = new MySettings();
string myPath = "new.xml";
XmlSerializer  s = new XmlSerializer(typeof(mySettings));

Use StreamReader class.

StreamReader streamReader = new StreamReader(myPath);
mySettings = (TVSettings)x.Deserialize(streamReader);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements