Reputation: 1124
I have a Class A and Class B that contains List of class A objects.
public class Item
{
public string X{ get; set; }
public string Y{ get; set; }
}
public class ItemCollection
{
List<Item> items = new List<Item>();
//Some methods
}
I can serialize it by:
IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml", FileMode.Create, isfile);
DataContractSerializer ser = new DataContractSerializer(itemlist.items.GetType());
XmlWriter writer = XmlWriter.Create(ifs);
ser.WriteObject(writer, itemlist.items);
But while deserializing it, I get "... Root element is missing." error.
IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml", FileMode.Open, isfile);
DataContractSerializer ser = new DataContractSerializer(itemlist.Items.GetType());
XmlReader reader=XmlReader.Create(ifs);
itemlist.items= (List<Item>)ser.ReadObject(reader);
Is there any other/better way of serializing/deserializing one class that contains list/collection of another class?
Upvotes: 1
Views: 1387
Reputation: 1063413
It looks to me like the problem is simply that you are wiping the file when you open it to deserialize, via FileMode.Create
. So of course the root element is missing: it is empty. You probably have the FileMode.Create
and FileMode.Open
inverted between the serialize/deserialize. And then add a few using
for good measure.
The serialize should use FileMode.Create
, to truncate or create the file fresh for new data.
The deserialize should use FileMode.Open
, to look at the existing data.
Upvotes: 1