2013-01-11 120 views
-2

我知道這個問題已經被問過,但我有奇怪的問題,我不知道該怎麼做: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)。

編輯:我想反序列化一個對象,有可能嗎?

+0

它失敗在哪一行? – James

+0

你的XML是否形成良好? – Oded

+1

你可以顯示對象嗎? – scartag

回答

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); 
+0

在實際情況中,我想序列化爲MyClass並反序列化爲對象,這有可能嗎? – karaxuna

+0

@karaxuna這對我來說似乎沒有意義。把它當作一個對象? 'object b = XmlHelper.Deserialize (a)'?或者你的意思是你想運行反序列化器不知道編譯時哪種類型? –

+0

是的,當我反序列化它時,我不知道它是類型 – karaxuna