Monday, June 03, 2013

Serialize object or list of objects using xDocument

This works for any serializable type or list of serializable type and deserialize back.


XDocument doc = new XDocument();

using (var writer = doc.CreateWriter())


    var serializer = new DataContractSerializer(objToSerialize.GetType());

    serializer.WriteObject(writer, objectToSerialize);


Var objectXml = doc.ToString();


To Deseralize xml back to type T.


DataContractSerializer ser = new DataContractSerializer(typeof(T));

return  (T)ser.ReadObject(xmlDocument.CreateReader(), true);



you need to refer using System.Xml.Serialization; in your class type.






No comments: