We are currently developping an application using XmlSerializer from the .NET framework.
Here is the structure of our classes:
[XmlInclude(typeof(TimeLineMediaClass))]
[XmlInclude(typeof(ImageMediaClass))]
public abstract class MediaClass
{
public string filename { get; set; }
public string maintitle { get; set; }
public string subtitle { get; set; }
public Type typeOfMedia { get; set; }
}
[XmlInclude(typeof(AudioMediaClass))]
[XmlInclude(typeof(VideoMediaClass))]
public abstract class TimeLineMediaClass : MediaClass
{
public string title { get; set; }
public TimeSpan length { get; set; }
public string genre { get; set; }
}
public class AudioMediaClass : TimeLineMediaClass
{
public string artist { get; set; }
}
public class VideoMediaClass : TimeLineMediaClass
{
public string director { get; set; }
public string studios { get; set; }
}
public class ImageMediaClass : MediaClass
{
public string width { get; set; }
public string height { get; set; }
}
Several medias of different types are added to a List, and this is what we want to serialize.
This is how the serializer is instanciated:
XmlSerializer serializer = new XmlSerializer(typeof(List<MediaClass>));
But when we launch the program and try to serialize, an exception is thrown, stating that “AudioMediaClass was not expected”.
EDIT: A few things were missing in the code I have provided. I have added some corrections in it ; more details in comments.
You need to decorate your
MediaClassclass withIn your example above, you have the casing wrong on
TimelineMediaClassmeaning the sample won’t compile for me. If you remove it, or if you do have a different class with this name, you’ll get the error you describe.Once you correct the casing, it should work – it does for me [noting that I also had to remove the attribute for
ImageMediaClasswhich also doesn’t exist in your sample].