反序列化不起作用

时间:2013-08-02 13:03:30

标签: c# xml

这是xml流:

<?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; }
}

用于反序列化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列表。 问题在于列表本身:它是空的......

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:4)

另外,为了将来参考(使用Visual Studio 2012或WebEssentials插件),基于一些示例XML内容数据创建类的最简单方法之一是将其复制到剪贴板中,然后使用内置的在VS函数中: EDIT - &gt;选择性粘贴 - &gt;将XML作为类粘贴到新的类文件中。

  • 它为您遇到的错误留下了更少的空间和
  • 速度很快,你可以在几秒钟内准备好你的课程