Ian (Fluxtah) Warwick's blog RSS 2.0
# Friday, November 13, 2009

I wrote a small console application to test if this was possible and it turns out all you need is an XmlInclude attribute on the base type of the sub-types you are serializing.

In the following example Ninja and Customer inherit from Person, Person is decorated with the XmlInclude attribute for both Ninja and Customer.

class Program
 {
     static void Main(string[] args)
     {
         XmlSerializer serializer = new XmlSerializer(typeof(Stuff));
         Stuff stuff = new Stuff()
         {
             People = new List<Person>()
             {
                 new Person() { Name = "<b>Bob</b>", Type="Person" },
                 new Ninja() { Name = "Hiro", Type="Ninja", Weapon = "Shuriken" },
                 new Customer() { Name = "Fred", Type = "Customer", CustomerId = "1234"}
             }
         };

         serializer.Serialize(Console.Out, stuff);
     }
 }

 public class Stuff
 {
     public List<Person> People { get; set; }
 }

 [XmlInclude(typeof(Ninja)), XmlInclude(typeof(Customer))]
 public class Person
 {
     public string Type { get; set; }
     public string Name { get; set; }
 }

 public class Ninja : Person
 {
     public string Weapon { get; set; }
 }

 public class Customer : Person
 {
     public string CustomerId { get; set; }
 }
Friday, November 13, 2009 7:56:37 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
Archive
<November 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Ian Warwick
Sign In
Statistics
Total Posts: 31
This Year: 2
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2010, Ian Warwick
DasBlog theme 'Business' created by Christoph De Baene (delarou)