วันอังคารที่ 25 พฤษภาคม พ.ศ. 2553

Serialize and Deserialize from string.

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(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;
}

Or use text to StringReader instead

var xml = @"";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
var car = (Car)serializer.Deserialize(reader);
}

ไม่มีความคิดเห็น: