简体   繁体   中英

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.

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.

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:

 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. What am I doing wrong? Cheers

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 files are not generally 'appended to' due to the need for opening and closing tags. 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.

What your program needs to do is read in the already-existing XML file on startup and store that as a PodcastList() . Your program can then add to it (in memory) and save the whole list as a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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