How to use XmlSerializer in C#?

CsharpProgrammingServer Side Programming

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);
Published on 18-Sep-2018 13:59:05