Using WP7 & C#:
I’m trying to convert my object(s) to XML so I can then save that file to SkyDrive. I’ve tried following many examples without much luck. With this code I’m
public void ConvertObjectToXmlString()
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(App.ViewModel.vehicleItemsCollection.GetType());
System.Xml.XmlWriter xtw = System.Xml.XmlWriter.Create(ms);
//System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8);
xs.Serialize(xtw, App.ViewModel.vehicleItemsCollection[0]);
MessageBox.Show(xtw.ToString());
}
The error is in this line: xs.Serialize(xtw, App.ViewModel.vehicleItemsCollection[0]);
I have a collection and in my test there is only 1 item. However I can imagine that when I eventually release this code that I wouldn’t have the index [0] set.
The error states:
There was an error generating the XML document
When I go further into the error message I see the following:
Cannot assign object of type OilChangeApplication.vehicle to an object of type System.Collections.ObjectModel.ObservableCollection`1[[OilChangeApplication.vehicle, OilChangeApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
vehicleItemsCollection is a collection of vehicle… What do I need to do to get some XML so I can upload this?
The error seems very explicit with a slight translation from compiler speak:
Cannot assign object of type
OilChangeApplication.vehicleto an object of typeObservableCollection<OilChangeApplication.vehicle>.It means your indexing of the collection cause the error, here:
Because instead of passing an
ObservableCollection<...>as you told the serializer above in this part:new XmlSerializer(App.ViewModel.vehicleItemsCollection.GetType());, you’re passing an instance of your model class.Thus you can either just remove the
[0]or change the type you’re passing to the serializer and the error will disappear.or