holland
holland

Reputation: 2182

Can't deserialize from derrived class

I have the following class:

public class Label
{
    public string Name { get; set; }

    public List<Field> Fields { get; set; }

    public Label(){}
}

The List<Field> can contain derrived classes from Field, for example:

public class Image : Field
{
    public string Path { get; set; }
    public int MyProperty { get; set; }
}

public class Field
{
    int Xpos { get; set; }
    int Ypos { get; set; }
}

However, when I use the following XML:

<?xml version="1.0" encoding="utf-8"?>
  <Label>
    <Name>test</Name>

    <Fields>
        <Image></Image>
    </Fields>
</Label>

My deserialization code:

string xmlString = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "Label_1.xml");
var serializer = new XmlSerializer(typeof(Label), new XmlRootAttribute("Label"));
Label result;

using (TextReader reader = new StringReader(xmlString))
{
    result = (Label)serializer.Deserialize(reader);
}

And I deserialize it, the Field property from a Label only has the Field in it, not the Image. How can I get the derrived class Image to be added in the list of Fields? Now I'm only able to add Field classes and the Images are being ignored. Thanks for help!

EDIT

If I change my code to the following:

[XmlInclude(typeof(Image))]
public abstract class Field
{
    int Xpos { get; set; }
    int Ypos { get; set; }
    int Zindex { get; set; }
    Style Style { get; set; }
}

Nothing happens! :(

Upvotes: 1

Views: 82

Answers (2)

user6996876
user6996876

Reputation:

this should do the trick

    [XmlArrayItem(ElementName = "Field", Type = typeof(Field))]
    [XmlArrayItem(ElementName = "Image", Type = typeof(Image))]
    public List<Field> Fields { get; set; }

Upvotes: 1

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

Make Field abstract, implement it on Image and use the XmlIncludeAttribute

[XmlInclude(typeof(Image))]
public abstract class Field
{
    int Xpos; 
    int Ypos; 
}

Upvotes: 1

Related Questions