Deserialize from string instead TextReader

user278618 picture user278618 · Feb 27, 2010 · Viewed 157.3k times · Source

I want to change my code from:

string path = @"c:\Directory\test.xml";
XmlSerializer s = new XmlSerializer(typeof(Car));

TextReader r = new StreamReader(path);

Car car = (Car)s.Deserialize(r);
r.Close();

into code that would convert an XML to a string, and then convert string to the object Car.

Is this possible?

Answer

Elmer picture Elmer · Feb 27, 2010
public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();