Welcome to MSDN Blogs Sign in | Join | Help

SYSK 315: Generic Functions for Object ↔ XML Serialization/Deserialization

There are many reasons for custom serialization of an object into a human readable string (e.g. XML).  If you find yourself recreating the serialization/deserialization code every few weeks, perhaps, it’s time to save off the functions below into a class in a shared assembly J.

 

public static string ToXml<T>(T source)

{

    string result = null;

 

    using (System.IO.StringWriter sw = new System.IO.StringWriter())

    {

        using (System.Xml.XmlWriter writer = System.Xml.XmlTextWriter.Create(sw, null))

        {

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            serializer.Serialize(writer, source);

        }

 

        result = sw.ToString();

    }

 

    return result;           

}

 

public static T FromXml<T>(string xml)

{

    T result = default(T);

 

    if (string.IsNullOrEmpty(xml) == false)

    {

        using (System.IO.StringReader sr = new System.IO.StringReader(xml))

        {

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            result = (T) serializer.Deserialize(sr);

        }

    }           

 

    return result;

}

 

Published Tuesday, March 27, 2007 5:12 AM by irenak
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: SYSK 315: Generic Functions for Object ↔ XML Serialization/Deserialization

Tuesday, March 27, 2007 10:48 AM by Doug

How fast do these methods run?

# re: Reply to Doug

Tuesday, March 27, 2007 12:06 PM by irenak

I don't have any numbers at this time... But since it's a very good question, I put it on my list of things to do -- stay tuned, the answer will be posted in one of the upcoming blog posts in the next few days.

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker