我正在尝试序列化此类:

[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,但是这些想法都没有用。我不确定该怎么办。

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

最佳答案

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

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

关于c# - XmlSerializer.Serialize异常:“类型[type]不是预期的。”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19502118/

10-15 17:33