3

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

Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
James Ford
  • 949
  • 4
  • 12
  • 25

3 Answers3

4

Try that:

// 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();
Mentezza
  • 627
  • 5
  • 16
3

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; }
}
Adam Gritt
  • 2,654
  • 18
  • 20
3

I think you need to change your XmlSerializer to this:

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

Before you were trying to serialize a list of Models, you want to serialize a XML file into a Model, which contains a list of stuff.

Also, you need to change your ObjectList definition to

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

Corwin01
  • 479
  • 3
  • 7
  • 24