Skip to main content

C# utility class Serialize objects to and from XML strings.

// Person.cs
namespace ObjectSerializers
{
    using System;

    //
    // The class must be Serializable and public.
    [Serializable]
    public class Person
    {
        public string FirstName;
        public string LastName;
        public string Street;
        public string City;
        public string State;
        public string Zip;

        //
        // Empty constructor required for serialization.
        public Person() {}

        //
        // Initializing constructor
        public Person(string first_name, string last_name, string street, string city, string state, string zip)
        {
            FirstName = first_name;
            LastName = last_name;
            Street = street;
            City = city;
            State = state;
            Zip = zip;
        }
    }
}


namespace ObjectSerializers
{
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    public static class XmlSerializerUtil
    {
        private const string XmlIndentChars = "  ";
        private static readonly XmlWriterSettings XmlSettings;
        private static readonly XmlSerializerNamespaces XmlNamespaces;

        static XmlSerializerUtil()
        {
            XmlSettings = new XmlWriterSettings
            {
                ConformanceLevel = ConformanceLevel.Document,
                CheckCharacters = true,
                Indent = true,
                IndentChars = XmlIndentChars,
            };

            //
            // Omit doc namespaces (ref: https://stackoverflow.com/a/258974)
            XmlNamespaces = new XmlSerializerNamespaces();
            XmlNamespaces.Add(prefix: "", ns: "");
        }

        public static string Serialize(object obj)
        {
            return obj == null
                ? null
                : SerializeInternal(obj);
        }

        private static string SerializeInternal(object obj)
        {
            using (var ms = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(ms, XmlSettings))
                {
                    var serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(writer, obj, XmlNamespaces);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }

        public static T Deserialize<T>(string data) where T : class
        {
            return string.IsNullOrEmpty(data)
                ? null
                : DeserializeInternal<T>(data);
        }

        private static T DeserializeInternal<T>(string data) where T : class
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T) serializer.Deserialize(ms);
            }
        }
    }
}

//
// Usage:

namespace ObjectSerializers.Console
{
    using System;

    internal static class Program
    {
        private static void Main(string[] args)
        {
            var person = new Person
            {
                FirstName = "Jacob",
                LastName = "Smith",
                City = "Austin",
                State = "TX",
                Street = "ElmStreet"
            };

            var serializedXml = XmlSerializerUtil.Serialize(person);

            Console.WriteLine(serializedXml);

            // >>> Output
            //
            // <?xml version="1.0" encoding="utf-8"?>
            // <Person>
            //   <FirstName>Jacob</FirstName>
            //   <LastName>Smith</LastName>
            //   <Street>ElmStreet</Street>
            //   <City>Austin</City>
            //   <State>TX</State>
            // </Person>
            //
            // >>>

        }
    }
}



// namespace XmlSerialize
// {
//     using System;
//     using System.Text;
//     using System.Diagnostics;
//     using System.IO;
//     using System.Xml;
//     using SystemXmlSerializer = System.Xml.Serialization.XmlSerializer;

//     public static class XmlSerializationUtils
//     {
//         private static readonly XmlWriterSettings XmlSettings;

//         static XmlSerializationUtils()
//         {
//             XmlSettings = new XmlWriterSettings
//             {
//                 Encoding = Encoding.UTF8,
//                 Indent = true,
//                 IndentChars = "  ", // indent using 2 spaces
//                 CheckCharacters = false,
//                 OmitXmlDeclaration = true,
//                 ConformanceLevel = ConformanceLevel.Auto
//             };
//         }

//         public static string Serialize(object obj)
//         {
//             Debug.Assert(obj != null);

//             using (var sw = new StringWriter())
//             {
//                 Serialize(obj, sw);

//                 return sw.GetStringBuilder().ToString();
//             }
//         }

//         private static void Serialize(object obj, TextWriter output)
//         {
//             Debug.Assert(obj != null);
//             Debug.Assert(output != null);

//             var writer = XmlWriter.Create(output, XmlSettings);

//             try
//             {
//                 var serializer = new SystemXmlSerializer(obj.GetType());
//                 serializer.Serialize(writer, obj);
//                 writer.Flush();
//             }
//             finally
//             {
//                 writer.Close();
//             }
//         }

//         public static T Deserialize<T>(string serializedXml)
//         {
//             return (T) Deserialize(serializedXml, typeof(T));
//         }

//         private static object Deserialize(string serializedXml, Type type)
//         {
//             var serializer = new SystemXmlSerializer(type);

//             object result;

//             using (TextReader reader = new StringReader(serializedXml))
//             {
//                 result = serializer.Deserialize(reader);
//             }

//             return result;
//         }
//     }
// }

// ----------------------------------------------------------------
// Example Usage
// ----------------------------------------------------------------

// namespace XmlSerializerConsole
// {
//     using System;
//     using System.Collections.Generic;
//     using XmlSerialize;

//     public class Person
//     {
//         public Person() => Friends = new List<Person>();
//         public string Name { get; set; }
//         public DateTime BirthDay { get; set; }
//         public List<Person> Friends { get; set; }
//     }

//     internal static class Program
//     {
//         private static Person CreatePerson()
//         {
//             var person = new Person
//             {
//                 Name = "Jon LaBelle",
//                 BirthDay = DateTime.UtcNow
//             };

//             person.Friends.Add(new Person {Name = "Friend 1", BirthDay = DateTime.UtcNow});
//             person.Friends.Add(new Person {Name = "Friend 2", BirthDay = DateTime.UtcNow});
//             person.Friends.Add(new Person {Name = "Friend 3", BirthDay = DateTime.UtcNow});

//             return person;
//         }

//         public static void Main(string[] args)
//         {
//             var person = CreatePerson();

//             // Make XML:
//             var personSerialized = XmlSerializationUtils.Serialize(person);
//             Console.WriteLine(personSerialized);
//             Console.WriteLine();

//             //
//             // Make Object:
//             var personDeserialized = XmlSerializationUtils.Deserialize<Person>(personSerialized);
//             foreach (var friend in personDeserialized.Friends)
//             {
//                 Console.WriteLine("{0} has a friend named {1}.",
//                     personDeserialized.Name, friend.Name);
//             }

//             Console.WriteLine();
//             Console.ReadKey();
//         }
//     }
// }