[C#] Generic Xml Serialize & Deserialize

Here are some methods to help in serialize an object to xml string and then deserialize from xml string to the object.

The Serialize method:

 /// <summary>
        /// The serialize.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="xmlWriterSettings">
        /// The xml writer settings.
        /// </param>
        /// <typeparam name="T">
        /// The object of the type T.
        /// </typeparam>
        /// <returns>
        /// The value in <see cref="string"/> that correspond the xml.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// The value cannot be null.
        /// </exception>
        public static string Serialize<T>(T value, XmlWriterSettings xmlWriterSettings = null)
        {
            if (value == null)
            {
                throw new ArgumentException("value");
            }

            var serializer = new XmlSerializer(typeof(T));

            var settings = xmlWriterSettings ?? new XmlWriterSettings
            {
                Encoding = new UnicodeEncoding(false, false),
                Indent = false,
                OmitXmlDeclaration = false
            };

            using (var textWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }

                return textWriter.ToString();
            }
        }

 

The Deserialize method:

        /// <summary>
        /// The deserialize.
        /// </summary>
        /// <param name="xml">
        /// The xml.
        /// </param>
        /// <param name="xmlReaderSettings">
        /// The xml Reader Settings.
        /// </param>
        /// <typeparam name="T">
        /// The object of the type T.
        /// </typeparam>
        /// <returns>
        /// The object of the type <see cref="T"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// The xml value cannot be null.
        /// </exception>
        public static T Deserialize<T>(string xml, XmlReaderSettings xmlReaderSettings = null)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentException("xml");
            }

            var serializer = new XmlSerializer(typeof(T));

            var settings = xmlReaderSettings ?? new XmlReaderSettings();

            // No settings need modifying here
            using (var textReader = new StringReader(xml))
            {
                using (var xmlReader = XmlReader.Create(textReader, settings))
                {
                    return (T)serializer.Deserialize(xmlReader);
                }
            }
        }

 

 

Class that inherits from other class should be defined using the attributes

[Serializable]

and

[XmlInclude(typeof( ... ))]

For example:

[Serializable]
[XmlInclude(typeof(Child))]
public class Father
{
  // something
}


[Serializable]
public class Child : Father
{
  // something
}

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.