C# - Generic XML serialization/deserialization

By , 8/19/2012
(1 ratings)
This class (XMLHelper) is able to serialize a XML file to a serializable object and vice versa.
You find an example of how to use the class in the code section.

Author: Orbmu2k, translation by Michael List
Translate to VB
// Example class for a serializable object
public class SimpleData
{
    private string name = "";
    private string phone = "";

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public string Phone
    {
        get { return phone; }
        set { phone = value; }
    }
}

// Example how to use the class
public class SampleUsage
{
    private SimpleData data = new SimpleData();

    public void LoadSimpleData()
    {
        data = XMLHelper.DeserializeFromXMLFile<SimpleData>(@"simpledata.xml");
    }

    public void StoreSimpleData()
    {
        XMLHelper.SerializeToXMLFile<SimpleData>(data, @"simpledata.xml", Encoding.Unicode, true);
    }

}


public static class XMLHelper
    {
        public static string SerializeToXMLString<T>(T XMLObj, Encoding encoding, bool removeNamespace)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            MemoryStream memStrm = new MemoryStream();
            XmlTextWriter xmlSink = new XmlTextWriter(memStrm, encoding);
            xmlSink.Formatting = Formatting.Indented;

            if (removeNamespace)
            {
                XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
                xs.Add("", "");
                xmlSerializer.Serialize(xmlSink, XMLObj, xs);
            }
            else
                xmlSerializer.Serialize(xmlSink, XMLObj);

            return encoding.GetString(memStrm.ToArray());
        }

        public static void SerializeToXMLFile<T>(T XMLObj, string Filename, Encoding encoding, bool removeNamespace)
        {
            File.WriteAllText(Filename, SerializeToXMLString<T>(XMLObj, encoding, removeNamespace));
        }

        public static T DeserializeFromXMLString<T>(string XML) where T : new()
        {
            T XMLObj = new T();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(XML);
            XMLObj = (T)xmlSerializer.Deserialize(sr);
            return XMLObj;
        }

        public static T DeserializeFromXMLFile<T>(string Filename) where T : new()
        {
            if (!File.Exists(Filename))
                throw FileNotFoundException();

            return DeserializeFromXMLString<T>(File.ReadAllText(Filename));
        }

    }

Comments

 

Log in, to comment!