Wednesday, October 3, 2018

XML Serialization and Deserialization

Often we need to serialize and deserialize object back and forth to XML in application development with C#. Below are two generic method which are quite handy for such.

Serialize an object to XML string. 

string Object2Xml<T>(T obj)
{
    var sw = new StringWriter();
    var serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(sw, obj);
    return sw.ToString();
    
}

Deserialize and XML string  back to object.

T Xml2Object<T>(string xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(new StringReader(xml));
}
 

No comments:

Post a Comment