2013-06-25 14 views
0

爲deserializ我的XML字符串Deserializ XML字符串到C#對象爲我的課型EmailAccount

> <?xml version="1.0" encoding="utf-16"?> <ReceiveAccountSetting 
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
> xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <POP3>POP3</POP3> 
> <Server>webmail.in</Server> 
> <AccountId>[email protected]</AccountId> <Password>123</Password> 
> <EnableSSL>true</EnableSSL> <DefaultPort>25</DefaultPort> 
> </ReceiveAccountSetting> 

時嘗試deserilize提示錯誤 「有XML文檔中的錯誤(0,0)

我的班級

public class ReceiveAccountSetting 
    { 
     /// <summary> 
     /// Receiving Email 
     /// </summary> 
     //public int AccountType { get; set; } 
     public string POP3 { get; set; } 
     public string IMAP { get; set; } 
     public string Server { get; set; } 
     public string AccountId { get; set; } 
     public string Password { get; set; } 
     public bool EnableSSL { get; set; } 
     public int DefaultPort { get; set; } 
    } 

爲deserilization方法

public EmailAccount Deserialize(string xmlstring) 
     { 
      EmailAccount objEmail = new EmailAccount(); 
      XmlSerializer serializer = new XmlSerializer(typeof(EmailAccount)); 
      StringReader reader = new StringReader(xmlstring); 
      using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlstring))) 
      { 

       objEmail = (EmailAccount)serializer.Deserialize(stream); 
      } 
      objEmail = (EmailAccount)serializer.Deserialize(reader); 
      return objEmail; 

     } 
+1

XML字符串在每行之前是否包含'>'?因爲如果你試圖用你將遇到的問題反序列化它。 – BlargleMonster

+0

您正在獲取的異常的'InnerException'屬性應包含更詳細的錯誤消息。 – MiMo

+1

檢查你的XML是否在文件/文本的頂部有一個字節順序標記,如果它確實嘗試[刪除它](http://stackoverflow.com/questions/295472/how-do-i-remove -xxx-file-012-bom-character-from-my-xml-file) –

回答

0

將XML文件加載到C#中的XMLDocument中,然後使用SelectNodes方法將其轉換爲XML節點列表可能會更容易。這樣,您可以單獨訪問每個節點並獲取所需的數據。您可以使用此代碼加載文件:

Document = new XmlDocument(); 

     try 
     { 
      openFileDialog1.ShowDialog(); 
      Document.Load(openFileDialog1.FileName); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
     ListOfNodes = Document.SelectNodes("ReceiveAccountSettings"); 

哪裏ListOfNodes是的XmlNodeList類型變量

後您將文件,您可以訪問任何節點像列表的任何其他成員,並獲得它的屬性,子節點等。