Search code examples
c#xmldeserializationilist

Deserialize xml to IList c#


I am trying to deserialize some xml into an IList, but I am having problems. This is what I have done so far:

The XML:

<?xml version="1.0" encoding="utf-8"?>

<Animals>
    <Animal>
        <Name>Cow</Name>
        <Color>Brown</Color>
    </Animal>
</Animals>

The Model:

[XmlRoot("Animals")]
public class Model
{
    [XmlElement("Animal")]
    public IList<Animal> AnimalList { get; set; }
}

public class Animal
{
    [XmlElement("Name")]
    public string Name{ get; set; }
    [XmlElement("Color")]
    public string Color{ get; set; }
}

Deserialization:

FileStream fs = new FileStream("file.xml", FileMode.Open);
XmlReader xml = XmlReader.Create(fs);

XmlSerializer ser = new XmlSerializer(typeof(List<Model>));

var list = (List<Model>)ser.Deserialize(xml);

I get an invalid operation exception when running the code above. What am I doing wrong?

Thanks, James Ford


Solution

  • The problem is that you are using an IList<Animal>. You need to use a List<Animal> so that it knows the specific type to use.

    EDIT: Using the following code in LINQPad works perfectly. Only difference is I am loading the XML via string instead of file, but even when I change to a file it works fine. I just added the using for System.Xml.Serialization.

    void Main()
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
        <Animals>
            <Animal>
                <Name>Cow</Name>
                <Color>Brown</Color>
            </Animal>
        </Animals>";
    
        XmlReader reader = XmlReader.Create(new StringReader(xml));
    
        XmlSerializer ser = new XmlSerializer(typeof(Model));
    
        var list = (Model)ser.Deserialize(reader);
        list.Dump();
    }
    
    // Define other methods and classes here
    [XmlRoot("Animals")]
    public class Model
    {
        [XmlElement("Animal")]
        public List<Animal> AnimalList { get; set; }
    }
    
    public class Animal
    {
        [XmlElement("Name")]
        public string Name{ get; set; }
        [XmlElement("Color")]
        public string Color{ get; set; }
    }