鉴于我有类的全名(作为字符串)和 XML(作为字符串),将 XML 反序列化为类的实例的正确方法是什么?需要注意的是,我在一个程序集中进行这项工作,而我想要反序列化的业务对象在另一个引用的程序集中。
问问题
1332 次
3 回答
2
using (StringReader strreader = new StringReader("xml of the object"))
{
using (XmlReader xmlreader = XmlReader.Create(strreader))
{
dynamic result = new XmlSerializer(Type.GetType("your type")).ReadObject(xmlreader);
}
}
于 2012-04-17T13:43:15.270 回答
1
/// <summary>
/// Deserialize string XML to the object of type T.
/// </summary>
/// <typeparam name="T">The type of the object where the xmlText are deserialized.</typeparam>
/// <param name="xmlText">The xml string to be deserialized to the object of type T.</param>
public static T DeserializeXMLToObject<T>(string xmlText)
{
if (string.IsNullOrEmpty(xmlText)) return default(T);
XmlSerializer xs = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(new UnicodeEncoding().GetBytes(xmlText)))
using (XmlTextReader xsText = new XmlTextReader(memoryStream))
{
xsText.Normalization = true;
return (T)xs.Deserialize(xsText);
}
}
您需要要反序列化的 XML 类型。
于 2012-04-19T03:15:42.597 回答
1
您不需要知道类名,而是需要对类类型的引用。
然后你可以像这样反序列化 XML:
StringReader read = new StringReader(xmlOfAnObject);
XmlSerializer serializer = new XmlSerializer(myObject.GetType());
XmlReader reader = new XmlTextReader(read);
WhateverTheType myObject = (WhateverTheType) serializer.Deserialize(reader);
reader.Close();
read.Close();
read.Dispose();
于 2012-04-17T13:38:59.540 回答