views:

299

answers:

2

Hi,

I wanna change my code from:

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

TextReader r=new new StreamReader(path);

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

into Code that would convert a xml to string , and then convert string to object car.

Is it possible??

+1  A: 

If you have the XML stored inside a string variable you could use a StringReader:

var xml = @"<car/>";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
    var car = (Car)serializer.Deserialize(reader);
}
Darin Dimitrov
+4  A: 

hi, i use this:

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>(string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

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

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

    return result;
}

greets!

Elmer
Better:public static T XmlDeserializeFromString<T>(string objectData){ return (T)XmlDeserializeFromString(objectData, typeof(T));}
Lee Treveil
Yes, that was a bug! fixed it...
Elmer
can I remove "this" from public static string XmlSerializeToString(this object objectInstance)??
You could remove 'this', but then the method is not an extension method anymore. By making the method an extension method, this is possible:string s = "blah!";string xml = s.XmlSerializeToString();note: be sure to reference the namespace of the static class that holds the extension methods in your usings, or the extension methods will not work!The only reason for using 'this' is to make it an extension method, it's completely safe to remove it.
Elmer