XmlSerializer 反序列化简单的对象列表

问题描述

这是我要反序列化的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);
    }