I have got the following code:
BaseContent.cs
public class BaseContent
{
// Some auto properties
}
News.cs
public class News : BaseContent
{
// Some more auto properties
}
Events.cs
public class Event : BaseContent
{
// Some more auto properites
}
GenericResponse.cs
public class GenericResponse<T>
{
[XmlArray("Content")]
[XmlArrayItem("NewsObject", typeof(News)]
[XmlArrayItem("EventObject", typeof(Event)]
public List<T> ContentItems { get; set; }
}
NewsResponse.cs
public class NewsResponse : GenericResponse<News> {}
EventResponse.cs
public class EventResponse : GenericResponse<Event> {}
As you can see, I have a base class BaseContent and two classes deriving from it. Next I have a generic response class, since the structure of the xml-files is always the same, but they differ in some properties.
I thought I can specify with the [XmlArrayItem] which name to use for a specific class. But now I get the error:
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type ‘System.Object’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’.
I can not add this reference, because I’m working on a Windows 8 App.
If I comment out one of the [XmlArrayItem] it is working well.
Anyone got an idea to solve this problem?
Update
I can not use DataContractSerializer, because I have to use XmlAttributes
Edit: Feel free to download the demo project
You didn’t provide all the properties for the objects, so allow me to add some – just as an example:
GenericResponse.cs could be defined this way – no need to specify the typeof for the array items:
And then you have the response classes:
Example 1: Serialize an EventResponse object
Output XML:
If you try the same with NewsResponse it will work fine. BTW I’m using my generic XmlSerializer, click on the link to know more about it.
XmlSerializer.cs: