Using DataContractSerializer or XmlSerializer for Serialization – [Windows 8 Store App]

Here is my sample for serialization.

Using DataContractSerializer

try
            {
                //this use the Local folder but can be other

                var applicationData = ApplicationData.Current;
                var storageFolder = applicationData.LocalFolder;

                var file = await storageFolder.CreateFileAsync("FileName.xml", CreationCollisionOption.ReplaceExisting);

                var dataContractSerializer = new DataContractSerializer(myObject.GetType());
                var memoryStream = new MemoryStream();
                dataContractSerializer.WriteObject(memoryStream, standOfCars);
                memoryStream.Seek(0, SeekOrigin.Begin);

                string serialized = new StreamReader(memoryStream).ReadToEnd();
                memoryStream.Dispose();

                var doc = new XmlDocument();
                doc.LoadXml(serialized);

                await doc.SaveToFileAsync(file);
            }
            catch (Exception exception)
            {
                // TODO handle the exception
            }




Using XmlSerializer

try
            {
                //this use the Local folder but can be other

                var applicationData = ApplicationData.Current;
                var storageFolder = applicationData.LocalFolder;
                var file = await storageFolder.CreateFileAsync("FileName.xml", CreationCollisionOption.ReplaceExisting);

                var dataContractSerializer = new XmlSerializer(myObject.GetType());
                var memoryStream = new MemoryStream();
                dataContractSerializer.Serialize(memoryStream, standOfCars);
                memoryStream.Seek(0, SeekOrigin.Begin);

                string serialized = new StreamReader(memoryStream).ReadToEnd();
                memoryStream.Dispose();

                var doc = new XmlDocument();
                doc.LoadXml(serialized);

                await doc.SaveToFileAsync(file);
            }
            catch (Exception exception)
            {
                // todo handle the exception
            }

I prefer the DataContractSerializer because if i use classes that implements interface i use the

[KnownType ( typeof (MyObject) ) ]

attribute and it works without problems. XmlSerializer give me some problem in the case when i have more than one level with interface implementation.

This topic:

c# XmlSerializer serialize generic List of interface

has similar problem that i had.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>