1

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! :(

Markinson
  • 2,077
  • 4
  • 28
  • 56
  • Possible duplicate of [C# XML serialization of derived classes](http://stackoverflow.com/questions/3326481/c-sharp-xml-serialization-of-derived-classes) – Curtis Lusmore Sep 14 '16 at 09:32

2 Answers2

1

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

[XmlInclude(typeof(Image))]
public abstract class Field
{
    int Xpos; 
    int Ypos; 
}
Caspar Kleijne
  • 21,552
  • 13
  • 72
  • 102
1

this should do the trick

    [XmlArrayItem(ElementName = "Field", Type = typeof(Field))]
    [XmlArrayItem(ElementName = "Image", Type = typeof(Image))]
    public List<Field> Fields { get; set; }
  • Thanks. This tag `represents an attribute that specifies the derived types that the XmlSerializer can place in a serialized array`, from [msdn](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx) ... where the serialized array is the above List –  Sep 14 '16 at 09:48