[英]Serialize XML text to an object
I have in my database many objects that have been serialized to XML format.我的数据库中有许多已序列化为 XML 格式的对象。 Now, I need to get those XML's back to objects again.
现在,我需要再次将这些 XML 恢复为对象。 What would be the best way to do this, using as little code as possible.
使用尽可能少的代码,最好的方法是什么。
I believe the best way is to build a generic method to convert any object.我相信最好的方法是构建一个通用方法来转换任何 object。 But obviously you need to be in control of which object will be converted from the returned XML.
但显然您需要控制哪个 object 将从返回的 XML 转换。
public T SerializeStringToObject(string XML)
{
T convertedObject;
try
{
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (System.IO.StringReader objetoXML = new System.IO.StringReader(XML))
{
convertedObject = (T)xml.Deserialize(objetoXML);
objetoXML.Close();
}
return convertedObject;
}
catch (Exception ex)
{
throw ex;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.