将ArrayList值保存到XML C#

时间:2013-10-21 07:21:46

标签: c# arraylist streamreader streamwriter

我有ArrayListnabídka,我必须使用流编写器将所有内容从此ArrayList保存到XML文件,并在启动应用程序时使用流阅读器将XML文件加载到ArrayList。有谁知道怎么做? (是的,我知道我不应该使用ArrayList,但我必须用它来完成这个项目。)

2 个答案:

答案 0 :(得分:2)

下面是一个如何实施的例子

  ArrayList sampleList = new ArrayList();
    sampleList.Add(" ");
    //Add your elements

    //StreamWriter initialized with append mode
    StreamWriter streamwriter = new StreamWriter(" INSERT PATH OF XML HERE ", true);

    for (int i = 0; i < sampleList.Count; i++)
    {
        //Elements are written into the file here, remember not to forget the xml structure 
        streamwriter.WriteLine(sampleList[i]);
    }

    //You have to close the streamwriter or you have to flush to make sure the text is saved
    streamwriter.Close();

我希望我能帮到你

答案 1 :(得分:0)

也可能:

var xmlSerializer = new XmlSerializer(typeof(ArrayList), new Type[] { typeof(YourType) });

但是对于序列化,最好有一个List<t>。 序列化的好处是易于阅读,您甚至可以在语言/应用程序之间轻松共享整个对象。