从string反序列化而不是TextReader
我想从以下位置更改我的代码:
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转换为string的代码,然后将string转换为对象Car。
这可能吗?
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>();
如果您将XML存储在stringvariables中,则可以使用StringReader :
var xml = @"<car/>"; var serializer = new XmlSerializer(typeof(Car)); using (var reader = new StringReader(xml)) { var car = (Car)serializer.Deserialize(reader); }
1-liner,将XMLstringtext
和yourType
作为预期的对象types。 与其他答案没有太大区别,只是压缩到1行:
object result = new XmlSerializer(typeof(yourType)).Deserialize(new StringReader(text));
无耻地从一个xmlstring的generics反序列化中复制
public static T DeserializeFromXmlString<T>(string xmlString) { var serializer = new XmlSerializer(typeof(T)); using (TextReader reader = new StringReader(xmlString)) { return (T) serializer.Deserialize(reader); } }
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; }