Deserialize xml for IList C #

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

XML:

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

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

      

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

      

An invalid operation exception is thrown when you run the above code. What am I doing wrong?

Thanks, James Ford

+3


source to share


3 answers


The problem is with what you are using IList<Animal>

. You need to use List<Animal>

so that it knows the specific type.

EDIT: Using the following code in LINQPad works great. The only difference is that I am loading the XML via a string instead of a file, but even when I go to the file it works fine. I just added a usage 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; }
}

      

+3


source


Try the following:



// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Model>));

// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(@"C:\file.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

// Load the object saved above by using the Deserialize function
List<Model> LoadedObj = (List<Model>)SerializerObj.Deserialize(ReadFileStream);

// Cleanup
ReadFileStream.Close();

      

+4


source


I think you need to change your XmlSerializer like this:

XmlSerializer ser = new XmlSerializer(typeof(Model));

Before trying to serialize a list of models, you want to serialize an XML file into a model containing a list of things.

Also, you need to change the definition of ObjectList to

public List<Animal> AnimalList { get; set; }

+3


source







All Articles