Search code examples
.netxmlxml-serializationxmlserializer

XmlSerializer deserialize simple object lists


This is the xml I want to deserialize:

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

I am using this code:

    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);
    }

The problem is, that the component node is found but the health node seems not to be found.


Solution

  • after trying a lot i came to this working solution:

        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);
        }