Reputation: 8054
I'm trying to serialize this class:
[XmlRoot("ArrayOfEvent")]
public class EventList
{
public EventList()
{
}
public EventList(IEnumerable<Event> items)
{
Items = items;
}
[XmlArray("")]
public IEnumerable<Event> Items { get; set; }
}
Here's the Event
class contained in EventList.Items
:
public class Event
{
[XmlElement]
public string ID { get; set; }
[XmlElement]
public string Title { get; set; }
[XmlElement]
public string Description { get; set; }
[XmlElement]
public string Location { get; set; }
[XmlElement]
public DateTime? StartTime { get; set; }
[XmlElement]
public DateTime? EndTime { get; set; }
[XmlElement]
public bool? AllDay { get; set; }
}
And here's where the error occurs:
public static XmlDocument ToXmlDocument<T>(T obj)
{
var xmlDocument = new XmlDocument();
var nav = xmlDocument.CreateNavigator();
if (nav != null)
{
using (var writer = nav.AppendChild())
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, obj); //throws exception
}
}
return xmlDocument;
}
The XmlSerializer
gives me this error when calling Serialize()
:
The type Domain.EventList was not expected.
Use the XmlInclude or SoapInclude attribute to specify types that are not
known statically.
I've tried using [XmlInclude(typeof(EventList))]
on the EventList
class as well as the Event
class but neither of those ideas worked. I'm not sure what else to do.
Is anybody familiar with this issue? How can I resolve it? Thanks in advance.
Upvotes: 2
Views: 1738
Reputation: 1063338
Basically, lists are kinda special to XmlSerializer
. You will have a lot more success if you declare the DTO to have a concrete list type, for example:
[XmlArray("")]
public List<Event> Items { get; set; }
Upvotes: 2