简体   繁体   中英

Same properties but different class name - XML Serialization

Is it possible to have common class to consume this XML? Both are API response from different routes

<Employee>
 <FirstName>...</FirstName>
 <LastName>...</LastName>
 <Age>...</Age>
 <DOB>...</DOB>
</Employee>

<Customer>
 <FirstName>...</FirstName>
 <LastName>...</LastName>
 <Age>...</Age>
 <DOB>...</DOB>
</Customer>

I am looking for something like

[XMLAlias="Employee","Customer"]
public class User
{
 public string FirstName { get; set; }
 public string LastName{ get; set; }
 public int Age{ get; set; }
 public DateTime DOB{ get; set; }
}

Or atleast

[XMLAlias="Employee"]
public class Customer
{
 public string FirstName { get; set; }
 public string LastName{ get; set; }
 public int Age{ get; set; }
 public DateTime DOB{ get; set; }
}

I suggest to have separate Employee and Customer classes, derived from base User class with common properties.

In future you can meet a situation, when one of the xml/class will have additional specific fields. So:

public class User
{
 public string FirstName { get; set; }
 public string LastName{ get; set; }
 public int Age{ get; set; }
 public DateTime DOB{ get; set; }
}

public class Employee : User
{
}

public class Customer : User
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM