iLemming
iLemming

Reputation: 36242

IXmlSerializable

Could you guys help me I have a problem with deserialization via 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);
        }
 }

And the xml itself looks like:

<Accounts>
   <Session UserName="18SRO" Password="shalom99">
     <Schedule>
      <StartAt>0001-01-01T09:30:00</StartAt>
      <EndAt>0001-01-01T16:00:00</EndAt>
    </Schedule>
  </Session>
</Accounts>

Upvotes: 1

Views: 1476

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063619

Re inherited fields... if you switch to DataContractSerializer, then fields are "opt in" rather than "opt out" - but you lose the ability to specify attributes (everything is an element). A trivial example:

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

    public int ThisIsntSerialized {get;set;}
}

However - adding unexpected subclasses is a pain for both XmlSerializer and DataContractSerializer. Both can do it, but it isn't pretty...

Upvotes: 1

micahtan
micahtan

Reputation: 19180

Since you've defined the classes, you should just be able to use XML Serialization attributes, and use the default XML deserializer.

Your structure doesn't look overly complicated, is there any particular reason you're not using serialization attributes instead of manually deserializing?

Upvotes: 1

Related Questions