Geeks With Blogs
Łukasz Kuryło's blog

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;
        }
    }
Posted on Wednesday, August 17, 2011 2:01 PM useful snippets | Back to top


Comments on this post: Useful snippet for serializing/deserializing data

# re: Useful snippet for serializing/deserializing data
Requesting Gravatar...
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
Left by Alan Dean on Aug 17, 2011 2:29 PM

Comments have been closed on this topic.
Copyright © Łukasz Kuryło | Powered by: GeeksWithBlogs.net