带有接口的类中的XmlSerializer空属性

时间:2016-07-21 14:53:57

标签: c# .net xml serialization ienumerable

我正在使用API​​ XML响应,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<artists itemsPerPage="30">
  <artist id="a0d9633b">
    <url>http://www.somesite.com/3df8daf.html</url>
  </artist>
</artists>

为了反序列化,我使用了类:

[SerializableAttribute]
[XmlTypeAttribute(TypeName = "result")]
public abstract class Result
{
    private int _itemsPerPage;

    [XmlAttributeAttribute(AttributeName = "itemsPerPage")]
    public int ItemsPerPage
    {
        get { return this._itemsPerPage; }
        set { this._itemsPerPage = value; }
    }
}

[SerializableAttribute]
[XmlTypeAttribute(TypeName = "artists")]
[XmlRootAttribute(ElementName = "artists")]
public class Artists : Result, IEnumerable<Artist>
{
    private List<Artist> _list;

    [XmlElementAttribute(ElementName = "artist")]
    public List<Artist> List
    {
        get { return this._list; }
        set { this._list = value; }
    }

    public Artists()
    {
        _list = new List<Artist>();
    }

    public void Add(Artist item)
    {
        _list.Add(item);
    }

    IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); }

    public IEnumerator<Artist> GetEnumerator()
    {
        foreach (Artist artist in _list)
            yield return artist;
    }
}

[SerializableAttribute]
[XmlTypeAttribute(TypeName = "artist")]
[XmlRootAttribute(ElementName = "artist")]
public class Artist
{
    private string _mbid;
    private string _url;

    [XmlAttributeAttribute(AttributeName = "mbid")]
    public string MBID
    {
        get { return this._mbid; }
        set { this._mbid = value; }
    }

    [XmlElementAttribute(ElementName = "url")]
    public string Url
    {
        get { return this._url; }
        set { this._url = value; }
    }

    public Artist() { }
}

这就是我反序列化的方式:

XmlSerializer serializer = new XmlSerializer(typeof(Artists));
Artists result = (Artists)serializer.Deserialize(new StreamReader("artists.xml"));

所以,问题是,当我进行反序列化时,ItemsPerPage没有所需的(30)值(默认值为0)。但是,如果我删除IEnumerable<Artist>界面并反序列化艺术家,则会显示该值。我可以删除界面,只使用Artists方法离开IEnumerator<Artist> GetEnumerator(),所以一切都会好的,Artists仍然可以预先处理,但不再是IEnumerable<Artist>。这不是我想要的。 问题不在基类中,因为我可以将属性ItemsPerPage传递给Artists类,反序列化结果也是一样的。

如何将Artists仍为IEnumerable<Artist>的ItemsPerPage值反序列化?

0 个答案:

没有答案