2013-08-02 21 views
9

這是XML流:deserialising不起作用

<?xml version="1.0" encoding="utf-8" ?> 
<historydetails> 
    <taskEvent> 
     <eventtype>Transitions</eventtype> 
     <historyevent>Task moved</historyevent> 
     <details>From 'Requested' to 'In Validation'</details> 
     <author>NAme</author> 
     <entrydate>01 Jul 13, 11:34</entrydate> 
     <historyid>2620</historyid> 
    </taskEvent> 
    <taskEvent> 
     <eventtype>Updates</eventtype> 
     <historyevent>Subtask marked done</historyevent> 
     <details>Subtask: visualise status and versions</details> 
     <author>NAme2</author> 
     <entrydate>21 Jun 13, 10:16</entrydate> 
    <historyid>2588</historyid> 
    </taskEvent> 
</historydetails> 

相應的類看起來是這樣的:

public class historydetails 
{ 
    [XmlElement("taskEvent")] 
    List<taskEvent> eventList = new List<taskEvent>(); 
} 

public class taskEvent 
{ 
    string eventtype { get; set; } 
    string historyevent { get; set; } 
    string details { get; set; } 
    string author { get; set; } 
    string entrydate { get; set; } 
    string historyid { get; set; } 
} 

代碼deserialise的XML(字符串替換包含XML代碼):

XmlSerializer deserializer = new XmlSerializer(typeof(historydetails));        
object obj = obj = deserializer.Deserialize(stringToStream(replacement));   
historydetails XmlData = (historydetails)obj; 

方法stringToStream

private MemoryStream stringToStream(string input) 
{ 
    byte[] byteArray = Encoding.ASCII.GetBytes(input); 
    MemoryStream stream = new MemoryStream(byteArray); 
    return stream; 
} 

我得到的結果如下: 對象XmlData被創建並且有一個taskEvents列表。 問題是在列表本身:它是空的......

+3

您是否嘗試過自己填充物和其序列以XML來比較?如果這是您的元素層次結構的問題,您會立即注意到。 –

+0

除非你嘗試{/ * fail * /} catch(Exception ex){ex.ToString();),否則「它不工作」的問題幾乎是無法解析的。 }'並將'ToString'的結果添加到您的問題中。 – Will

+1

請問,他沒有收到錯誤。他正在獲得一個有效的XML對象,但它是空的。 – BlargleMonster

回答

10

你必須讓公衆

public class historydetails 
{ 
    [XmlElement("taskEvent")] 
    public List<taskEvent> eventList = new List<taskEvent>(); 
} 

    public class taskEvent 
{ 
    public string eventtype { get; set; } 
    public string historyevent { get; set; } 
    public string details { get; set; } 
    public string author { get; set; } 
    public string entrydate { get; set; } 
    public string historyid { get; set; } 
} 
4

作爲成員一邊,以供將來參考(與Visual Studio 2012或WebEssentials插件) ,根據一些示例XML內容數據創建類的最簡單方法之一是將其複製到剪貼板,然後使用內置的VS函數:編輯 - >選擇性粘貼 - >將XML作爲類粘貼到新的類文件。

  • 它留下更少的空間像你遇到的一個錯誤
  • 它速度快,你有你的類準備在幾秒鐘
+0

這是否使用XSD生成器工具? – Aphelion

+1

好問題,我現在還不確定。我一直在IL的環境中進行實施,但我放棄了。知道它是如何完成是很有趣的。 –