News


In one of my previous posts I have used my custom code to serialize and deserialized data to/from XmlDocument class.

Examples of use:

XmlDocument extensions=//some xml document taken from db
List<FileExtension> result = 
   SerializationUtils.DeSerializeXmlToObject<List<FileExtension>>(extensions);

List<FileExtension> extensions=//some new objects to save to database
XmlDocument serializedExtensions =
                SerializationUtils.SerializeObjectToXml<List<FileExtension>>(extensions);

The full code for this snippets:

    public static class SerializationUtils
    {
        public static T DeSerializeXmlToObject<T>(XmlDocument xmlDoc)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(xmlDoc.InnerXml);
            T result = (T)serializer.Deserialize(reader);

            return result;
        }

        public static XmlDocument SerializeObjectToXml<T>(T obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringWriter w = new StringWriter();
            serializer.Serialize(w, obj);
            XmlDocument result = new XmlDocument();
            string xmlContent = w.ToString();
            result.LoadXml(xmlContent);
            return result;
        }
    }

Comments

Gravatar # re: Useful snippet for serializing/deserializing data
Posted by Alan Dean on 8/17/2011 2:29 PM
I have similar (test-driven) implementations for XmlSerialize(...) [1] and XmlDeserialize<T>(...) in Cavity.

[1] http://code.google.com/p/cavity/source/browse/trunk/src/ClassLibraries/Core/Object.ExtensionMethods.cs

[2] http://code.google.com/p/cavity/source/browse/trunk/src/ClassLibraries/Core/String.ExtensionMethods.cs
Comments have been closed on this topic.