This blog is moved to
http://amalhashim.wordpress.com

Wednesday, May 18, 2011

Serialize Multiobject ArrayList to XML

This is a code snippet which shows how to Serialize an ArrayList to XML. ArrayList contains objects of different types.

using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
AListWrapper wrapper = new AListWrapper();

XmlSerializer mySerializer = new XmlSerializer(typeof(AListWrapper));

StreamWriter myWriter = new StreamWriter("c:\\myFileName.xml");

mySerializer.Serialize(myWriter, wrapper);
myWriter.Close();
}
}

public class Animal
{
public string Type { get; set; }
public int Age { get; set; }
}

public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public string Address { get; set; }
}

[XmlRoot("ArrayList")]
public class AListWrapper
{
[XmlElement(Type = typeof(Employee)),
XmlElement(Type = typeof(Animal))]
public ArrayList list = new ArrayList();

public AListWrapper()
{
Animal animal = new Animal()
{
Age = 1,
Type = "Dog"
};

Employee emp = new Employee()
{
Address = "Address",
Name = "SomeName",
Salary = 2000.50
};

list.Add(animal);
list.Add(emp);
}
}
}

2 comments:

Fen said...

I was wondering why we dont see you in the VB forums anymore AMAL!

Congrats on your MVP! :)


FthrJACK

A.m.a.L Hashim said...

Thanks Fen.