XML Serialization of an Arraylist.#
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)
{
RunIt();
}
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();
al.Add(v1);
al.Add(v2);
al.Add(v3);

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

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

Console.WriteLine(((
MyData)ax[0]).a.ToString());
Console.WriteLine(((
MyData)ax[1]).a.ToString());
Console.WriteLine(((
MyData)ax[2]).a.ToString());

}
}
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.

Saturday, August 09, 2008 7:59:02 PM (GTB Daylight Time, UTC+03:00) #    Comments [0]  | 

 

Comments are closed.
All content © 2012, Levent YILDIZ
On this page
This site
Calendar
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

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

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: