XmlSerializer.Serialize异常:“不期望类型[类型]。”

时间:2013-10-21 18:33:58

标签: c# xml serialization xml-serialization

我试图序列化这个类:

[XmlRoot("ArrayOfEvent")]
public class EventList
{
    public EventList()
    {

    }

    public EventList(IEnumerable<Event> items)
    {
        Items = items;
    }

    [XmlArray("")]
    public IEnumerable<Event> Items { get; set; }
}

此处包含Event中包含的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; }
}

以下是发生错误的地方:

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;
}

调用XmlSerializer时,Serialize()给了我这个错误:

The type Domain.EventList was not expected. 
Use the XmlInclude or SoapInclude attribute to specify types that are not 
known statically.

我已尝试在[XmlInclude(typeof(EventList))]课程以及EventList课程中使用Event,但这些想法都没有奏效。我不确定还能做什么。

有人熟悉这个问题吗?我该如何解决?提前谢谢。

1 个答案:

答案 0 :(得分:2)

基本上,列表对XmlSerializer有点特殊。如果您声明DTO具有具体的列表类型,您将获得更多成功,例如:

[XmlArray("")]
public List<Event> Items { get; set; }