【问题标题】:XmlSerializer.Serialize exception: "The type [type] was not expected."XmlSerializer.Serialize 异常:“类型 [type] 不是预期的。”
【发布时间】:2013-10-21 18:33:57
【问题描述】:

我正在尝试序列化这个类:

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

    }

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

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

这是EventList.Items中包含的Event类:

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.

我尝试在EventList 类和Event 类上使用[XmlInclude(typeof(EventList))],但这些想法都不起作用。我不知道还能做什么。

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

【问题讨论】:

  • 也许是个愚蠢的评论,但你使用了 [Serializable] 属性?
  • @gleng XmlSerializer[Serializable] 一点也不感兴趣
  • @gleng 是的,我确实尝试过,但没有效果。

标签: c# xml serialization xml-serialization


【解决方案1】:

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

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

【讨论】:

  • 不幸的是,这也没有改变任何东西。同样的错误。
  • @kehrk 首先,它只识别(作为列表)实现 IList&lt;T&gt; 的事物(或者它可能是 IList 加上一个非对象索引器 - 这是一种常见的框架模式) - 但其次,它只适用于具体的列表类型:如果你用一个接口尝试它,它会抛出一个异常,说它对此不满意。估计是重构的缘故。有些序列化程序不会强加这些要求,但这就是 XmlSerializer 的工作原理
  • @kehrk 我尝试了这个例子——它适用于我的场景,它是列表。你能给出一个完整的(可运行的)失败的例子吗?
  • 我将所有相关代码添加到 OP。希望能帮助到你。感谢您的调查。
  • @kehrk 与编辑:你能显示调用 ToXmlDocument&lt;T&gt;(T obj) 的代码吗?我想知道您作为参数传递的东西是否不是EventList,而是其他东西 - objectISomeInterfaceSomeBaseType
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多