我知道这个问题已被提出,但我有一个奇怪的问题,我无法弄清楚该怎么做:
public static class XmlHelper
{
public static T Deserialize<T>(string xml)
{
using (var sr = new StringReader(xml))
{
var xs = new XmlSerializer(typeof(T));
return (T)xs.Deserialize(sr);
}
}
public static string Serialize(object o)
{
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw))
{
var xs = new XmlSerializer(o.GetType());
xs.Serialize(xw, o);
return sw.ToString();
}
}
}
}
[Serializable]
public class MyClass
{
public string Property1 {get;set;}
public int Property2 {get;set;}
}
我正在序列化课程:
var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<object>(a);
错误:XML文档中存在错误(1,41)。
编辑:我想反序列化一个as对象,是否可能?
答案 0 :(得分:1)
您没有传递正确的序列化类型,请将代码更改为:
public static string Serialize<T>(T o)
{
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw))
{
var xs = new XmlSerializer(typeof(T));
xs.Serialize(xw, o);
return sw.ToString();
}
}
}
...
// we don't need to explicitly define MyClass as the type, it's inferred
var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<MyClass>(a);