从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。

这可能吗?

5 Solutions collect form web for “从string反序列化而不是TextReader”

 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,将XMLstringtextyourType作为预期的对象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; } 
  • 将XML数据分解为SQL Server数据库列的最佳方法
  • 为XML编码文本数据的最佳方法
  • 我可以在XML中绘制矩形吗?
  • 添加空格到布局
  • 在log4j xmlconfiguration中使用系统环境variables
  • 如何检查string是否是有效的XML元素名称?
  • 最好的XMLparsing器的PHP
  • 具有多个条件的XPath
  • XPath,XQuery和XPointer之间的区别
  • 你如何比较两个XML文档?
  • 使用python创build一个简单的XML文件