Search code examples
c#.netxmlserializer

How to generate an XML using XMLSerializer?


I would like to generate an XML using XMLSerializer. I have an abstract Base class which is being inherited by other classes.

 public abstract class Base
    {
      public string Name {get; set;}
      public int ID {get; set;}

      public Base(string Name, int ID)
      {
         this.Name = Name;
         this.ID = ID;
      }
    }



 public class HR: Base
    {      
      public HR(string Name, int ID): Base(Name,ID)
      {
      }
    }

    public class IT : Base
    {
      public IT(string Name, int ID): Base(Name,ID)
      {
      }
    }

I am not sure how to generate an XML of format

<Employee>
 <HR>
  <Name> </Name>
  <ID> </ID>
 </HR>
 <IT>
  <Name> </Name>
  <ID> </ID>
 </IT>
</Employee>

I apologise for the vague question. I have never used XMLSerializer before and not sure how to proceed with it. Any help would be greatly appreciated.

Thanks


Solution

  • As I read your xml, it seems you want to serialize a list of Employee. I have a solution for you if your list is a member of a class (not directly serializing the list).

    public abstract class Employee
    {
        public string Name { get; set; }
        public int ID { get; set; }
        public Employee(string Name, int ID)
        {
            this.Name = Name;
            this.ID = ID;
        }
    }
    
    public class HR : Employee
    {
        public HR() : base(null, 0) { } // default constructor is needed for serialization/deserialization
        public HR(string Name, int ID) : base(Name, ID) { }
    }
    public class IT : Employee
    {
        public IT() : base(null, 0) { }
        public IT(string Name, int ID) : base(Name, ID) { }
    }
    
    public class Group
    {
        [XmlArray("Employee")]
        [XmlArrayItem("HR",typeof(HR))]
        [XmlArrayItem("IT",typeof(IT))]
        public List<Employee> list { get; set; }
    
        public Group()
        {
            list = new List<Employee>();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Group grp = new Group();
            grp.list.Add(new HR("Name HR", 1));
            grp.list.Add(new IT("Name IT", 2));
    
            XmlSerializer ser = new XmlSerializer(typeof(Group));
            ser.Serialize(Console.Out, grp);
        }
    }
    

    And the output is :

    <?xml version="1.0" encoding="ibm850"?>
    <Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Employee>
        <HR>
          <Name>Name HR</Name>
          <ID>1</ID>
        </HR>
        <IT>
          <Name>Name IT</Name>
          <ID>2</ID>
        </IT>
      </Employee>
    </Group>
    

    Very similar to your desired output, excepted one more element at the root "Group".

    Deserialize with the same XmlSerializer(typeof(Group)) should work as well.