Today i received a question about how to serialize an arraylist through xmlserialization.
Then i rapidly wrote a class named MyData which has 2 properties
public class MyData
public int a;
public string b;
public MyData()
{ }
public MyData(int _a, string _b)
a = _a;
b = _b;
Then generated some instances and added them to an arraylist in the main project.
class Program
static void Main(string[] args)
static void RunIt()
MyData v1 = new
MyData(0, "Zero");
MyData v2 = new MyData(1, "One");
MyData v3 = new MyData(2, "Two");

ArrayList al = new ArrayList();

XmlSerializer s = new XmlSerializer(typeof(ArrayList));
string path = @"c:\seri.xml";
TextWriter tx = new StreamWriter(path, true);
s.Serialize(tx, al);

FileStream fs = File.OpenRead(@"c:\seri.xml");
ArrayList ax = (ArrayList)s.Deserialize(fs);


When i ran the code i got the error, {"The type ConsoleApplication1.MyData was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."} which was the main question.

After some search i found out tht XmlSerializer was not aware of the type of MyData class and thus i got the above error.
To make XmlSerializer aware of a custom type, you should use one of it's constructer methods while u'r creating the object.
While creating XmlSerializer object i just added type type of my arraylist includes.
XmlSerializer s = new XmlSerializer(typeof(ArrayList),new Type[]{typeof(MyData)});
Ps: also i found out tht if u're developing this kind of code and having these type of errors, everytime u run the project make sure u delete the serialization file.Cause previous failed attemps may cause the right code to throw exceptions.

Comments are closed.