1

你们能帮我吗?我在通过 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>
4

2 回答 2

1

由于您已经定义了类,您应该能够使用 XML 序列化属性,并使用默认的 XML 反序列化器。

您的结构看起来并不过分复杂,是否有任何特殊原因您不使用序列化属性而不是手动反序列化?

于 2009-06-26T18:49:59.717 回答
1

重新继承的字段...如果您切换到DataContractSerializer,则字段是“选择加入”而不是“选择退出”-但是您将失去指定属性的能力(一切都是元素)。一个简单的例子:

[DataContract(Name="foo")]
public class Foo
{
    [DataMember(Name="bar")]
    public string Bar { get; set; }

    public int ThisIsntSerialized {get;set;}
}

XmlSerializer但是,添加意外的子类对于和来说都是一种痛苦DataContractSerializer。两者都可以,但它并不漂亮......

于 2009-06-26T19:59:16.520 回答