将xml反序列化为复杂对象

时间:2017-05-06 18:36:34

标签: c# xml object deserialization .net-core

我能够像Feed那样从Feed中绑定简单的信息,但是尝试解析复杂的对象总是为空。我的映射中我做错了什么?

饲料

[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class Feed
{
    [XmlElement("author")]
    Author Author { get; set; }

    [XmlElement("entry")]
    List<Entry> Entries { get; set; }

    [XmlElement("id")]
    public string Id { get; set; }
}

作者

[XmlType("author")]
public class Author
{
    [XmlElement("name")]
    public string Name { get; set; }
    [XmlElement("email")]
    public string Email { get; set; }
}

条目

[XmlType("entry")]
public class Entry
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("published")]
    DateTime Published { get; set; }
    [XmlElement("updated")]
    DateTime Updated { get; set; }
    [XmlElement("title")]
    public string Title { get; set; }
}

反序列化

        using (Stream stream = res.GetResponseStream())
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Feed));
            feed = (Feed)serializer.Deserialize(stream);
        }

1 个答案:

答案 0 :(得分:1)

我怀疑“Feed”类定义位。

尝试以下方式,看看它是否有效。

  1. 声明您的“作者”类和列表类public
  2. 尝试在构造函数中构建Author和List,如下面的代码所示。

    [XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
    public class Feed
    {
          //ADD A CONSTRUCTOR AND CREATE LIST AND AUTHOR
          public Feed()
          {
             Author1 = new Author();
             Entries = new List<Entry>();
    
          }
    
          [XmlElement("author")]
          public Author Author1 { get; set; }
    
          [XmlElement("entry")]
          public List<Entry> Entries { get; set; }
    
          [XmlElement("id")]
          public string Id { get; set; } 
    }