将xml反序列化为列表

时间:2018-10-10 19:41:26

标签: c#

我有一个基于以下模型的普通列表:

型号:

public class ProjectHistoryModel
{
    public int  JobNumber { get; set; }
    public int DesignKey { get; set; }
    public string ProjectName { get; set; }
}

在课堂上,我有这样一个模型的列表:

public List<ProjectHistoryModel> ProjectHistoryModel = new List<ProjectHistoryModel>();

然后我将该列表另存为xml文件:

序列化列表:

public static string SerializeObject<T>(this T value)
{
    if (value == null)
    {
        return string.Empty;
    }
    try
    {
        var xmlserializer = new XmlSerializer(typeof(T));
        var stringWriter = new StringWriter();
        using (var writer = XmlWriter.Create(stringWriter))
        {
            xmlserializer.Serialize(writer, value);
            return stringWriter.ToString();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("An error occurred", ex);
    }
}

所以我保存列表,只是将其发送给该方法为:

var historyXml = ProjectHistoryModel.SerializeObject();
XML.HistoryProjects = historyXml;
XML.SaveXML();

现在我的问题是:我如何反序列化该xml并再次转换为列表? 我尝试这样的操作,但被卡住了:

  public static List<string> Load()
        {
            var xmlList = XML.HistoryProjects;

            using (var stream = System.IO.File.OpenRead(FileName))
            {
                var serializer = new XmlSerializer(xmlList));
                return serializer.Deserialize(stream) as [xmlList];
            }
        }

致谢

2 个答案:

答案 0 :(得分:1)

您只需要使用StringReader而不是writer来做相反的事情。

public static T DeserializeObject<T>(this string source) 
{
    if (string.IsNullOrEmpty(source))
    {
        return default(T);
    }
    try
    {
        var xmlserializer = new XmlSerializer(typeof(T));
        var stringReader = new StringReader(source);
        using (var reader = XmlReader.Create(stringReader))
        {
            var result = xmlserializer.Deserialize(reader);
            return (T)result;
        }
    }
    catch (Exception ex)
    {
        throw new Exception("An error occurred", ex);
    }
}

然后通过以下方式调用它:

    var input = new List<ProjectHistoryModel>();
    var serialized = input.SerializeObject();
    var output = serialized.DeserializeObject<List<ProjectHistoryModel>>();

这里是指向working example on DotNetFiddle的链接。

答案 1 :(得分:0)

您必须将对象反序列化为序列化对象的类型。将xmlList反序列化为List<ProjectHistoryModel>,并将方法Load的返回类型更改为List<ProjectHistoryModel>。看看是否可行。