使用WP7 & C#:試圖序列化對象到XML
我想我的對象(S)轉換爲XML,所以我可以再保存該文件到SkyDrive。我試過很多例子,但沒有多少運氣。有了這個代碼,我
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());
}
的錯誤是在這一行:xs.Serialize(xtw, App.ViewModel.vehicleItemsCollection[0]);
我有一個集合,並在我的測試中只有1項。但是我可以想象,當我最終發佈此代碼時,我不會設置索引[0]。
的錯誤狀態: 時出錯生成XML文檔
當我進一步去到錯誤消息我看到以下內容: 不能分配型OilChangeApplication.vehicle的對象的對象類型System.Collections.ObjectModel.ObservableCollection`1 [[OilChangeApplication.vehicle,OilChangeApplication,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]。
vehicleItemsCollection是一個車輛的集合...我需要做些什麼來獲得一些XML,所以我可以上傳這個?
什麼是您的vehicleItem模型?如果內存服務,您需要在模型中做一些元數據標記,以便序列化程序知道如何處理對象類型。 –
是指屬性?現在它沒有。 – webdad3
@ Dillie-O我想你正在討論在模型類定義中添加'[XmlSerializable]'(又名XmlSerializableAttribute)。這很有用,但不是這個錯誤的原因。 – jv42