我如何在 C# 中反序列化 xml

how can i deserialize xml in C#

我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization; 
using System.Xml;
using System.Xml.Linq;
using System.Threading.Tasks;


namespace PlaylistEditor.Writers
{
    public class XMLPlaylistWriter : IPlaylistWriter
    {
        public void Save(Playlist ply, string filePath)
        {
            StreamWriter writer = null;
            try
            {
                XmlSerializer xs = new XmlSerializer(ply.GetType());
                writer = new StreamWriter(filePath);
                xs.Serialize(writer, ply);

            }
            finally
            {
                if (writer != null)
                    writer.Close();
                writer = null;
            }
        }


        public Playlist Load(string filePath)
        {
          return null;    

        }


    }
}

我写信加载 "return null;" 我序列化了那个和 运行 代码,但我做不到并找到反序列化的方法。感谢您的帮助。

您需要使用XmlReader

private Playlist Load(string filename)
{
    Playlist playlist;
    // Create an instance of the XmlSerializer specifying type and namespace.
    var serializer = new
    XmlSerializer(typeof(Playlist));

    // A FileStream is needed to read the XML document.
    using (var fs = new FileStream(filename, FileMode.Open))
    {
        using (var reader = XmlReader.Create(fs))
        {
            playlist = (Playlist) serializer.Deserialize(reader);
            fs.Close();
        }
    }
    return playlist;
}

参考自 msdn => link