我知道這個問題已經被問過,但我有奇怪的問題,我不知道該怎麼做:XML序列化和反序列化失敗
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)。
編輯:我想反序列化一個對象,有可能嗎?
它失敗在哪一行? – James
你的XML是否形成良好? – Oded
你可以顯示對象嗎? – scartag