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 st开发者_运维问答ring, and then convert string to the object Car.
Is this possible?
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>();
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);
}
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
static T DeserializeXml<T>(string sourceXML) where T : class
{
var serializer = new XmlSerializer(typeof(T));
T result = null;
using (TextReader reader = new StringReader(sourceXML))
{
result = (T) serializer.Deserialize(reader);
}
return result;
}
Shamelessly copied from Generic deserialization of an xml string
public static T DeserializeFromXmlString<T>(string xmlString)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlString))
{
return (T) serializer.Deserialize(reader);
}
}
精彩评论