从字符串反序列化而不是 TextReader
Posted
技术标签:
【中文标题】从字符串反序列化而不是 TextReader【英文标题】:Deserialize from string instead TextReader 【发布时间】:2011-01-21 19:16:22 【问题描述】:我想更改我的代码:
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();
将 XML 转换为字符串,然后将字符串转换为对象 Car。
这可能吗?
【问题讨论】:
【参考方案1】: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;
使用它:
//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();
//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();
【讨论】:
更好:public static T XmlDeserializeFromStringpublic static T XmlDeserializeFromString<T>(this string objectData) return (T)XmlDeserializeFromString(objectData, typeof(T));
我要编辑主帖。
StringReader
是缺失的部分。谢谢。【参考方案2】:
如果您将 XML 存储在字符串变量中,则可以使用 StringReader:
var xml = @"<car/>";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
var car = (Car)serializer.Deserialize(reader);
【讨论】:
using(var reader = new StringReader(xml)) return (Car)new XmlSerializer(typeof(Car)).Deserialize(reader);【参考方案3】:1-liner,将 XML 字符串 text
和 YourType
作为预期的对象类型。与其他答案差别不大,只是压缩为 1 行:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
【讨论】:
我会在使用后关闭 StringReader。【参考方案4】: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;
【讨论】:
【参考方案5】:无耻抄袭 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);
【讨论】:
以上是关于从字符串反序列化而不是 TextReader的主要内容,如果未能解决你的问题,请参考以下文章
如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?