Serialize and Deserialize Xml to Disk Using Generics

If you need to serialize and deserialize your objects and persist them
to disk, the the code below is an easy way to accomplish this. The
GetObjectTypes function correctly detects types so that the serializer
will do it’s job correctly. Without this you could run into problems
(as I did).

VB

    ”’ <summary>

    ”’ Deserializes from XML file.

    ”’ </summary>

    ”’ <typeparam name=”T”>Type</typeparam>

    ”’ <param name=”fileName”>Name of the file.</param>

    ”’ <returns></returns>

    Public Shared Function DeserializeFromXmlFile(Of T)(ByVal fileName As String) As T

        Return Deserialize(Of T)(My.Computer.FileSystem.ReadAllText(fileName))

    End Function

 

    ”’ <summary>

    ”’ Deserializes the specified XML.

    ”’ </summary>

    ”’ <typeparam name=”T”>Type</typeparam>

    ”’ <param name=”xml”>The XML.</param>

    ”’ <returns></returns>

    Public Shared Function Deserialize(Of T)(ByVal xml As String) As T

        Dim serializer = New XmlSerializer(GetType(T))

 

        Return DirectCast(serializer.Deserialize(New XmlTextReader(New StringReader(xml))), T)

    End Function

 

    ”’ <summary>

    ”’ Serializes obj to XML file.

    ”’ </summary>

    ”’ <param name=”obj”>The obj.</param>

    ”’ <param name=”fileName”>Name of the file.</param>

    Public Shared Sub SerializeToXmlFile(ByVal obj As Object, ByVal fileName As String)

        My.Computer.FileSystem.WriteAllText(fileName, Serialize(obj), False)

    End Sub

 

    ”’ <summary>

    ”’ Serializes the specified obj to xml.

    ”’ </summary>

    ”’ <param name=”obj”>The obj.</param>

    ”’ <returns></returns>

    Public Shared Function Serialize(ByVal obj As Object) As String

 

        Dim returnXml As String = String.Empty

 

        Dim serializer = New XmlSerializer(obj.[GetType](), GetObjectTypes(obj).ToArray())

 

        Using writer As New StringWriter(CultureInfo.CurrentCulture)

            serializer.Serialize(New XmlTextWriter(writer), obj)

 

            returnXml = writer.ToString()

        End Using

 

        Return returnXml

    End Function

 

    Private Shared Function GetObjectTypes(ByVal input As Object) As List(Of Type)

 

        Dim types = New List(Of Type)()

 

        Dim currentAssembly = input.[GetType]().Assembly

 

        Dim currentType As Type = input.[GetType]()

 

        ‘Query our types. We could also load any other assemblies and

        ‘query them for any types that inherit from the currentType

 

        For Each tempType As Type In currentAssembly.GetTypes()

            If Not tempType.IsAbstract AndAlso Not tempType.IsInterface AndAlso currentType.IsAssignableFrom(tempType) Then

                types.Add(tempType)

            End If

        Next

 

        Return types

    End Function

C#

        /// <summary>

        /// Deserializes from XML file.

        /// </summary>

        /// <typeparam name=”T”>Type</typeparam>

        /// <param name=”fileName”>Name of the file.</param>

        /// <returns></returns>

        public static T DeserializeFromXmlFile<T>(string fileName)

        {

            return Deserialize<T>(Microsoft.VisualBasic.FileIO.FileSystem.ReadAllText(fileName));

        }

 

        /// <summary>

        /// Deserializes the specified XML.

        /// </summary>

        /// <typeparam name=”T”>Type</typeparam>

        /// <param name=”xml”>The XML.</param>

        /// <returns></returns>

        public static T Deserialize<T>(string xml)

        {

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

 

            return (T)serializer.Deserialize(new XmlTextReader(new StringReader(xml)));

        }

 

        /// <summary>

        /// Serializes obj to XML file.

        /// </summary>

        /// <param name=”obj”>The obj.</param>

        /// <param name=”fileName”>Name of the file.</param>

        public static void SerializeToXmlFile(object obj, string fileName)

        {

            Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText(fileName, Serialize(obj), false);

        }

 

        /// <summary>

        /// Serializes the specified obj to xml.

        /// </summary>

        /// <param name=”obj”>The obj.</param>

        /// <returns></returns>

        public static string Serialize(object obj)

        {

 

            string returnXml = string.Empty;

 

            var serializer = new XmlSerializer(obj.GetType(), GetObjectTypes(obj).ToArray());

 

            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))

            {

                serializer.Serialize(new XmlTextWriter(writer), obj);

 

                returnXml = writer.ToString();

            }

 

            return returnXml;

        }

 

        private static List<Type> GetObjectTypes(object input)

        {

 

            var types = new List<Type>();

 

            var currentAssembly = input.GetType().Assembly;

 

            Type currentType = input.GetType();

 

            //Query our types. We could also load any other assemblies and

            //query them for any types that inherit from the currentType

 

            foreach (Type tempType in currentAssembly.GetTypes())

            {

                if (!tempType.IsAbstract && !tempType.IsInterface && currentType.IsAssignableFrom(tempType))

                {

                    types.Add(tempType);

                }

            }

 

            return types;

        }

Tip Submitted By: David McCarter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s