C# 反序列化不起作用
这是xml流:C# 反序列化不起作用,c#,xml,C#,Xml,这是xml流: <?xml version="1.0" encoding="utf-8" ?> <historydetails> <taskEvent> <eventtype>Transitions</eventtype> <historyevent>Task moved</historyevent> <details>From 'Requ
<?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>
stringToStream方法
private MemoryStream stringToStream(string input)
{
byte[] byteArray = Encoding.ASCII.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
我得到的结果如下:
对象XmlData已生成,并且存在taskEvents列表。
问题在于列表本身:它是空的…您必须公开成员
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; }
}
公共类历史详细信息
{
[XmlElement(“taskEvent”)]
public List eventList=新列表();
}
公共类任务事件
{
公共字符串事件类型{get;set;}
公共字符串historyevent{get;set;}
公共字符串详细信息{get;set;}
公共字符串作者{get;set;}
公共字符串入口日期{get;set;}
公共字符串historyid{get;set;}
}
作为旁白,为了将来参考(使用Visual Studio 2012或WebEssentials插件),根据一些示例XML内容数据创建类的最简单方法之一是将其复制到剪贴板,然后使用内置的VS函数:编辑->粘贴特殊->将XML作为类粘贴到新的类文件中
- 它为您遇到的错误和
- 速度很快,几秒钟后你就可以把课准备好了
尝试{/*fail*/}catch(Exception ex){ex.ToString();}
并将ToString
的结果添加到你的问题中,否则“它不起作用”的问题几乎无法回答。威尔,他不会出错。他得到的是一个有效的XML对象,但它是空的。我自己尝试填充它,但出现了错误,当然是非常愚蠢的错误=在描述类中的属性时没有公共属性。非常感谢您在反序列化XML的代码中还泄漏了内存流。使用使用(var stream=stringToStream(replacement)){object obj=deserializer.Deserialize(stream);historydetails XmlData=(historydetails)obj;}
这是否使用XSD生成器工具?好问题,我现在不确定。我一直在IL中寻找实现,但我放弃了。知道它是怎么做的会很有趣。
private MemoryStream stringToStream(string input)
{
byte[] byteArray = Encoding.ASCII.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
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; }
}