A LinkedList can’t be serialized using XmlSerializer.
Now, how to however save/retrieve data from a serialized objet LinkedList. Should I implement custom serialization?
What I tried to do:
using System.Xml.Serialization;
[Serializable()]
public class TestClass
{
private int _Id;
private string _Name;
private int _Age;
private LinkedList<int> _linkedList = new LinkedList<int>();
public string Name {
get { return _Name; }
set { _Name = value; }
}
public string Age {
get { return _Age; }
set { _Age = value; }
}
[XmlArray()]
public List<int> MyLinkedList {
get { return new List<int>(_linkedList); }
set { _linkedList = new LinkedList<int>(value); }
}
}
What I’ve obtained(addind name, age and some items in the mylinkedlist):
<?xml version="1.0"?>
<TestClass
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>testName</Name>
<Age>10</Age>
<MyLinkedList />
</TestClass>
So, the items in the linked list hadn’t been serialized… 🙁
One possibility would be the creation of a serializable collection that contains the same objects as the linked list. E.g. (untested):
Then serialize
listinstead. This isn’t going to create a lot of overhead ifFoois a reference type, and you don’t care about the fact that insertions/deletions are now more expensive b/c you’re only using theList<T>to hold references to the data for serialization and deserialization purposes. When you pull it out of the serialized stream, you can just turn it back into aLinkedList<T>to get all those advantages you were using a linked list for in the first place.Here’s a little console app I just whipped up to demonstrate. I did it in VS2008, but I don’t think I used anything surprising– just the array initialization syntax to save some vertical space.
Sample Code:
And the main application code:
This kicks the following out to the console: