使用继承反序列化XML

时间:2015-10-14 07:08:43

标签: c# xml class deserialization

我需要反序列化以下XML:

<ContactMethods>
    <ContactMethod Method="PhoneContact"> (00) 000 0000 </ContactMethod>
    <ContactMethod Method="WorkContact">  (00) 000 0000 </ContactMethod>
</ContactMethods>

目前,我有一个名为ContactMethod的基类,其中包含所有联系方式共享的字段。我还为每种类型的联系人提供了类,每个类都继承了ContactMethod基类。我在下面提供了我的课程。

public class Applicant
{
  [System.Xml.Serialization.XmlArray]
    [System.Xml.Serialization.XmlArrayItem(ElementName="Dependant")]
  public List<string> Dependants;

  //CONTACT
  [System.Xml.Serialization.XmlArrayItem("PhoneContact", typeof(PhoneContact))]
  public List<ContactMethod> ContactMethods;
}

public class ContactMethod
{
  public string ContactMethodId { get; set; }
  public string Value;
  public Boolean PhoneFacsimile;
  public Boolean PhoneSms;
  public Boolean PhoneVoice { get; set; }
  public Boolean EmailHtml;

  public ContactMethod()
  {
    this.PhoneFacsimile = false;
    this.PhoneSms       = false;
    this.PhoneVoice     = false;
    this.EmailHtml      = false;
  }
}

public class PhoneContact : ContactMethod
{
  public PhoneContact()
  {
    this.ContactMethodId  = "PH";
    this.PhoneVoice       = true;
  }
}

public class WorkContact : ContactMethod
{
  public WorkContact()
  {
    this.ContactMethodId  = "W";
    this.PhoneVoice       = true;
  }
}

我的目标是使用每个联系方法类型的构造函数来设置默认值,如联系方式ID。那么如何使用Method =“?”将每个联系方法映射到适当的contactMethod类型类在XML字符串中。

0 个答案:

没有答案