你们能帮我吗?我在通过IXmlSerializable进行反序列化时遇到了问题
var ArrayOfAccounts = new Accounts(); //This class structure I'm trying to read
Class Accounts:List<Session>{ }
Class Shedule{
public DateTime StartAt { get; set; }
public DateTime EndAt { get; set; }
}
Class Session:IXmlSerializable {
public string Name{get;set;}
public string Pass{get;set;}
public List<Shedule> Shedules = new List<Shedule>();
public void ReadXml(System.Xml.XmlReader reader){
//AND HERE IS A PROBLEM. I don't know how to implement right code here. I've tried
//code below, but this one works for the first account only, and doesn't restore others
Schedules.Clear();
XmlReader subR = reader.ReadSubtree();
if (reader.MoveToAttribute("Name"))
Name = reader.Value;
if (reader.MoveToAttribute("Password"))
Password = reader.Value;
reader.MoveToContent();
while (subR.ReadToFollowing("Schedule"))
{
XmlSerializer x = new XmlSerializer(typeof(Schedule));
object o = x.Deserialize(subR);
if (o is Schedule) Schedules.Add((Schedule)o);
}
}xml本身看起来像这样:
<Accounts>
<Session UserName="18SRO" Password="shalom99">
<Schedule>
<StartAt>0001-01-01T09:30:00</StartAt>
<EndAt>0001-01-01T16:00:00</EndAt>
</Schedule>
</Session>
</Accounts>发布于 2009-06-26 18:50:00
既然您已经定义了类,那么您应该能够使用XML序列化属性,并使用默认的XML反序列化程序。
您的结构看起来并不太复杂,是否有什么特殊的原因使您不使用序列化属性而是手动反序列化?
发布于 2009-06-26 19:59:17
重新继承字段...如果你切换到DataContractSerializer,那么字段是“选择加入”而不是“选择退出”--但是你失去了指定属性的能力(所有东西都是一个元素)。一个简单的例子:
[DataContract(Name="foo")]
public class Foo
{
[DataMember(Name="bar")]
public string Bar { get; set; }
public int ThisIsntSerialized {get;set;}
}然而,添加意想不到的子类对于XmlSerializer和DataContractSerializer来说都是一件痛苦的事情。两个人都能做到,但这不是很好。
https://stackoverflow.com/questions/1050603
复制相似问题