简体   繁体   English

在C#中序列化XML

[英]Serialize XML in C#

I'm basically trying to add podcasts to an XML file and eventually retrieve them from that same XML, using the data in different parts of the application. 我基本上是在尝试将播客添加到XML文件中,并最终使用应用程序不同部分的数据从同一XML中检索播客。

I successfully write the data to the XML but every time I reboot the application (debug) and press the "submit" button the XML file resets to 0 entries. 我已成功将数据写入XML,但每次重新启动应用程序(调试)并按“提交”按钮时,XML文件都会重置为0个条目。

The submit code: 提交代码:

  PodcastList podList = new PodcastList();

    private void btnAddPod_Click(object sender, EventArgs e)
    {
        var podUrl = txtAddPod.Text; 
        var podName = txtEnterName.Text;

        podList.AddPod(podUrl, podName, 0);

        Xml.SaveListData(podList.GetPodcastList(), "Podcasts.xml");
    }

Save to XML: 保存为XML:

 public static void SaveListData(object obj, string filename)
    {
        var serializer = new XmlSerializer(obj.GetType());

        using (var stream = new StreamWriter(filename))
        {
            serializer.Serialize(stream, obj);
        }
    }

I guess the applications creates a new XML-file every time I press submit and has fresh objects. 我猜每当我按下提交并有新对象时,应用程序都会创建一个新的XML文件。 What am I doing wrong? 我究竟做错了什么? Cheers 干杯

PodcastList podList = new PodcastList(); PodcastList podList = new PodcastList(); is at the class level. 在课堂上。

If you want to maintain the state , Reload the XML file Deserialize the file to PodcastList in the Constructor or at the time of the load, Then you will be able to retain and reuse the collection and rewrite the data back to XML file. 如果要保持状态,请重新加载XML文件在构造器中或加载时将文件反序列化到PodcastList,然后,您将能够保留和重用集合并将数据重写回XML文件。

XML files are not generally 'appended to' due to the need for opening and closing tags. 由于需要打开和关闭标签,因此通常不将XML文件附加到“文件”中。 As opposed to say, other types of text file like log files where appending makes a bit more sense. 相对而言,其他类型的文本文件(如日志文件)在其中添加更有意义。

When you call serializer.Serialize the whole file gets overwritten. 当您调用serializer.Serialize ,整个文件将被覆盖。

What your program needs to do is read in the already-existing XML file on startup and store that as a PodcastList() . 您的程序需要做的是在启动时读入已经存在的XML文件,并将其存储为PodcastList() Your program can then add to it (in memory) and save the whole list as a file. 然后,您的程序可以添加到其中(在内存中),并将整个列表另存为文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM