Xml Serialization of a collection

kingelessar

Active member
Joined
Jul 14, 2003
Messages
26
Location
Netherlands, Europe
Hey guys,

I am busy creating a Log program in C#. I want to log files to be saved in Xml. I want to do this with Xml Serialization. This is my LogFile class:
Code:
[XmlRoot("logfile")]
	public class LogFile
	{
		[XmlElement("title",typeof(string))]
		public string LogTitle;

		[XmlArray("entries")]
		[XmlArrayItem("entry",typeof(LogEntry))]
		public ArrayList Entries;

		public LogFile()
		{
			Entries = new ArrayList();
		}

		public void WriteEntry(string user, string text)
		{
			Entries.Add(new LogEntry(user,text));
		}
	}

	public class LogEntry
	{
		[XmlAttribute("dateandtime",typeof(DateTime))]
		public DateTime DateAndTime;

		[XmlAttribute("user",typeof(string))]
		public string User;

		[XmlText(typeof(string))]
		public string Text;

		public LogEntry(string user, string text)
		{
			DateAndTime = DateTime.Now;
			User = user;
			Text = text;
		}
	}
This is my (de)serialization code:
Code:
public void Serialize()
		{
			XmlSerializer s = new XmlSerializer(typeof(LogFile));
			TextWriter writer = new StreamWriter(file);
			s.Serialize(writer, mylog);
			writer.Close();
		}

		public void DeSerialize()
		{
			FileStream fs = new FileStream(file, FileMode.Open);
			XmlSerializer x = new XmlSerializer(typeof(LogFile));
			mylog = (LogFile)x.Deserialize(fs);
		}
When I make a new LogFile mylog object and add some entries (mylog.WriteEntry("John Doe","Logged on!")), and set the log file title (mylog.LogTitle = "My Log") and compile it and run it, it gives the following error:

An unhandled exception of type System.InvalidOperationException occurred in system.xml.dll

Additional information: There was an error reflecting XmlSerialization.LogFile.

I really dont understand why it doesnt work. Please help!

Thanx :confused:
 
Xml Serializer

Thanks,

But, what i would like to do is to serialize
a classe that can contain an Arraylist or
an Hashtable Object.

The Hashtable may contain object types
more complex than string (recursive serialization).

:)
 
Both the ArrayList and HashTable classes are marked with the
Serializable attribute, so as long as the classes in the collections
are also Serializable you shuld be all set.
 
Originally posted by Bucky
Both the ArrayList and HashTable classes are marked with the
Serializable attribute, so as long as the classes in the collections
are also Serializable you shuld be all set.

This is not the case when using XML serialization however. The XmlSerializer cannot serialize Hashtables, or any class that implements the IDictionary interface.
 
ehm for Xml serialization I never use the serializable attribute and everything works fine with simple classes, as long as i have an empty constructor

Thanx for ur responses.

Dennis
 
Back
Top