XmlSerializer 反序列化简单对象列表

XmlSerializer deserialize simple object lists

这是我要反序列化的xml:

<?xml version="1.0" encoding="utf-8" ?>
<units>  
  <entity>
    <component/>
    <health max="1000"/>   
  </entity>
</units>

我正在使用这个代码:

    public class component { }

    public class health : component { public int max { get; set; } }

    [XmlRoot("units")]
    public class units
    {
        [XmlElement("entity")]
        public List<entity> entity { get; set; }
    }

    public class entity
    {
        [XmlElement("component")]
        public List<component> component { get; set; }
    }

    void Read()
    {
        var x = new XmlSerializer(typeof(units), new[] { typeof(entity), typeof(health), typeof(component) });
        var fs = new FileStream("units.xml", FileMode.Open);
        XmlReader reader = new XmlTextReader(fs);
        var units = (units)x.Deserialize(reader);
    }

问题是,找到了组件节点,但是好像找不到健康节点。

经过多次尝试,我找到了这个可行的解决方案:

    public class component
    {
    }

    public class health : component
    {
        [XmlAttribute("max")]
        public int max { get; set; }
    }

    public class componentlist : List<component>
    {
    }

    [XmlRoot("units")]
    public class units
    {
        [XmlArray("entity")]
        [XmlArrayItem(typeof(component))]
        [XmlArrayItem(typeof(health))]
        public componentlist entity { get; set; }
    }

    public void Read()
    {
        var x = new XmlSerializer(typeof(units), new[] { typeof(componentlist), typeof(component), typeof(health) });
        var fs = new FileStream("units.xml", FileMode.Open);
        XmlReader reader = new XmlTextReader(fs);
        var units = (units)x.Deserialize(reader);
    }