This static class provides methods for Serializing and Deserializing .NET objects. This functionality is useful for taking an object down to a string for persistent storage or transport over the wire.

Namespace:  CA.Common.xml
Assembly:  CA.Common (in CA.Common.dll) Version: 1.0.0.0 (1.0.0.0)

Remarks

Serialisation of .NET objects is very useful. This simple class is extremely powerful enabling quick and fairly efficient methods to serialise just about any public .NET object. It is important to note that the serialisation will only serialise public properties and fields and that those fields must be publicly available for read and write (ie properties must have getters and setters) to Deserialise correctly using the default sterilisation. The code can control aspects of the serialisation using the serialization attributes. The examples given on the SerialiseObject(Object, XmlSerializerNamespaces) and DeSerialiseObject(String, Type) methods highlight the usage.

Full source code provided below

CopyFull Source Code for the XmlObjectSerialisation class
//Source code from the Code Associate C# code library, Full documentation and latest updates can be found
//@ http://www.codeassociate.com/caapi/
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace CA.Common.xml
{
    public static class XmlObjectSerialisation
    {

        public static string SerialiseObject(object obj, XmlSerializerNamespaces ns)
        {
            XmlSerializer ser = new XmlSerializer(obj.GetType());
            StringBuilder sb = new StringBuilder();
            StringWriter writer1 = new StringWriter(sb);
            XmlTextWriter writer = new XmlTextWriter(writer1);
            writer.Formatting = Formatting.None;
            ser.Serialize(writer, obj, ns);
            return(sb.ToString());
        }

        public static string SerialiseObject(object obj)
        {
            return (SerialiseObject(obj, true));
        }

        public static string SerialiseObject(object obj, bool useEmptyNameSpace)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            if (useEmptyNameSpace)
                ns.Add(string.Empty, string.Empty);
            return SerialiseObject(obj, ns);
        }

        public static object DeSerialiseObject(string obj, System.Type objtype)
        {
            XmlSerializer ser = new XmlSerializer(objtype);
            StringReader reader = new StringReader(obj);
            return (ser.Deserialize(reader));
        }


    }
}

Inheritance Hierarchy

System..::.Object
  CA.Common.xml..::.XmlObjectSerialisation

See Also