Tuesday, March 5, 2013

Serialize object to XML file or XML to object (Deserialize)

This code snippet shows how to serialize an object to an XML file.


            XmlSerializer xs = new XmlSerializer(MyObject.GetType());
            MemoryStream ms = new MemoryStream();
            xs.Serialize(ms, MyObject);


            StreamWriter sw = System.IO.File.CreateText("C:\\tmp\\custData.xml");
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string theContent = sr.ReadToEnd();

            sw.Write(theContent);
         
         
            sw.Close();
            sw.Dispose();

Deserialize an XML file to an object (assuming that you have the classes created):

                Object obj = new object();


                XmlSerializer xs = new XmlSerializer(objectDestination.GetType());
                FileStream fs = new FileStream(pathToXML, FileMode.Open);
                XmlReader xr = new XmlTextReader(fs);
             
                obj = xs.Deserialize(xr);
                fs.Close();

Here we have a method that takes the XML string as paramater returns an object of type T:

public static T DeserializeXMLToObject(string objectAsXml)
{
XmlSerializer xs = new XmlSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(objectAsXml)); XmlReader xr = new XmlTextReader(ms); T obj = (T)xs.Deserialize(xr); return obj;
}

No comments:

Post a Comment