简体   繁体   中英

XmlSerialization won't work

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 MediaClass class with

[XmlInclude(typeof(TimeLineMediaClass))]

In your example above, you have the casing wrong on TimelineMediaClass meaning 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 ImageMediaClass which also doesn't exist in your sample].

I copy your code, and run removing [XmlInclude(typeof(ImageMediaClass))] and correcting this attribute: [XmlInclude(typeof(TimelineMediaClass))] to [XmlInclude(typeof(TimeLineMediaClass))] . Now, running your code, it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM