9

这是 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 列表。问题出在列表本身:它是空的......

4

2 回答 2

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; }
}
于 2013-08-02T13:12:23.540 回答
4

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

  • 它为您遇到的错误留下的空间更少,并且
  • 速度很快,几秒钟内你就可以准备好你的课程
于 2013-08-02T13:19:26.517 回答