2013-12-14 55 views
0

我想救我的列表,以一個XML文件,所以後來我纔可以再次加載數據,如果我重新打開該程序。保存列表以XML

這是我嘗試保存數據的代碼:

public static void SerializeToXml<T>(T obj, string fileName) 
    { 
     using (var fileStream = new FileStream(@"C:\\Users\\Kevin\\Desktop\\Save.XML", FileMode.Create)) 
     { 
      var ser = new XmlSerializer(typeof(T)); 
      ser.Serialize(fileStream, obj); 
      fileStream.Close(); 
     } 
    } 

而且我用這個代碼來調用該函數:

Saving.SerializeToXml<List<Vara>>(minaVaror, @"C:\\Users\\Kevin\\Desktop\\Save.XML"); 

然而,當我按一下按鈕,試圖挽救數據,程序崩潰,我留下了這個錯誤/警告:

Barline_1.Vara is inaccessible due to its protection level. Only public types can be processed. 

而這是它的代碼行的complaning約:

var ser = new XmlSerializer(typeof(T)); 

的是什麼可能是錯的任何想法呢?

+0

作爲站點說明:什麼是在'SerializeToXml'中使用'fileName'? –

+0

您是否認爲'Barline_1'的定義與問題無關,因此您沒有發佈? –

回答

0

根據定義的XmlSerializer無法反序列化的列表或一個ArrayList 從Msdn

The XmlSerializer cannot deserialize the following: arrays of ArrayList and arrays of List<T>. 

所以,你可以序列化一個列表,但你不能反序列化列表

所以,你可以使用此代碼以XML序列化和反序列化的XML文件

namespace DataContractSerializerExample 
{ 
    using System; 
    using System.Collections; 
    using System.Collections.Generic; 
    using System.IO; 
    using System.Runtime.Serialization; 
    using System.Xml; 

    // You must apply a DataContractAttribute or SerializableAttribute 
    // to a class to have it serialized by the DataContractSerializer. 
    [DataContract(Name = "Vara", Namespace = "http://www.contoso.com")] 
    public class Vara 
    { 
     [DataMember()] 
     public double streckKod { get; set; } 
     [DataMember] 
     public string artNamn { get; set; } 
    } 

    public sealed class Test 
    { 
     private Test() { } 

     public static void Main() 
     { 
      List<Vara> minaVaror = new List<Vara>() { new Vara() { streckKod = 5.0, artNamn = "test1" }, new Vara() { streckKod = 5.0, artNamn = "test2" }, new Vara() { streckKod = 5.0, artNamn = "test3" } }; 
      string fileName = "test.xml"; 
      Serialize<List<Vara>>(fileName, minaVaror); 
      List<Vara> listDes = Deserialize<List<Vara>>(fileName); 






     } 

     public static void Serialize<T>(string fileName,T obj) 
     {   
      FileStream writer = new FileStream(fileName, FileMode.Create); 
      DataContractSerializer ser = 
       new DataContractSerializer(typeof(T)); 
      ser.WriteObject(writer, obj); 
      writer.Close(); 
     } 

     public static T Deserialize<T>(string fileName) 
     { 
      FileStream fs = new FileStream(fileName, 
      FileMode.Open); 
      XmlDictionaryReader reader = 
       XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()); 
      DataContractSerializer ser = new DataContractSerializer(typeof(T));       
      T des = 
       (T)ser.ReadObject(reader, true); 
      reader.Close(); 
      fs.Close(); 
      return des; 
     } 
    } 
} 

: 您應該添加引用到 C:\ Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.0 \ System.Runtime.Serialization.dll