Results 1 to 6 of 6

Thread: [2005] Serialize any class to Xml and vice-versa

Threaded View

  1. #1

    Thread Starter
    Fanatic Member MetalKid's Avatar
    Join Date
    Aug 2005
    Location
    Green Bay, Wisconsin
    Posts
    534

    [2005] Serialize any class to Xml and vice-versa

    A few classes cannot be serialized to XML because they do not support ISerializable. The most notable being the Dictionary class. However, if it can't serialize, it will just throw an exception about it.

    Code:
    using System.Xml;
    using System.Xml.Serialization;
    using System.IO;        
    
           public string Serialize<T>(T entity)
           {
                StringBuilder outputXml = new StringBuilder();
    
                if (typeof(T).IsSerializable)
                {
                    XmlSerializer ser = new XmlSerializer(typeof(T));
                    using (TextWriter stream = new StringWriter(outputXml))
                    {
                        ser.Serialize(stream, entity);
                    }
    
                    return outputXml.ToString();
                }
    
                return null;
            }
    
            public T Deserialize<T>(string xml)
            {
                T entity;
    
                if (typeof(T).IsSerializable)
                {
                    XmlSerializer ser = new XmlSerializer(typeof(T));
                    using (TextReader stream = new StringReader(xml))
                    {
                        entity = (T)ser.Deserialize(stream);
                    }
    
                    return entity;
                }
    
                return null;
            }
    Last edited by MetalKid; May 6th, 2009 at 09:52 AM.
    If your problem is solved, please use the Mark Thread As Resolved under Thread Tools!

    Show Appreciation. Rate Posts!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width