【问题标题】:xml serialization and Inherited Typesxml 序列化和继承类型
【发布时间】:2012-12-13 21:47:58
【问题描述】:

我收到错误“{”类型 Device1 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。"}"

目前我有:

public abstract class Device
{
   ..
} 

public class Device1 : Device
{ ... }

[Serializable()]
public class DeviceCollection : CollectionBase
{ ... }

[XmlRoot(ElementName = "Devices")]
public class XMLDevicesContainer
{
    private DeviceCollection _deviceElement = new DeviceCollection();

    /// <summary>Devices device collection xml element.</summary>
    [XmlArrayItem("Device", typeof(Device))]
    [XmlArray("Devices")]
    public DeviceCollection Devices
    {
        get
        {
            return _deviceElement;
        }
        set
        {
            _deviceElement = value;
        }
    }
}

我正在做:

        XMLDevicesContainer devices = new XMLDevicesContainer();
        Device device = new Device1();

        device.DeviceName = "XXX";
        device.Password = "Password";

        devices.Devices.Add(device);
        Serializer.SaveAs<XMLDevicesContainer>(devices, @"c:\Devices.xml", new Type[] { typeof(Device1) });

序列化器会:

   public static void Serialize<T>(T obj, XmlWriter writer, Type[] extraTypes)
    {
        XmlSerializer xs = new XmlSerializer(typeof(T), extraTypes);
        xs.Serialize(writer, obj);
    }

我在序列化器方法(xs.Serialize)的最后一行出现错误:“{”类型Device1不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。"}"

我尝试在 Device 类上编写 XmlInclude。没有帮助。 如果我换行

    [XmlArrayItem("Device", typeof(Device))] 

成为

     [XmlArrayItem("Device", typeof(Device1))]

然后它可以工作,但我想编写多个设备类型的数组。

【问题讨论】:

    标签: c# serialization xmlserializer inherited xmlinclude


    【解决方案1】:

    您必须为希望在 XMLDevicesContainer 类上可用的每个子类添加 XmlIncludeAttribute。

    [XmlRoot(ElementName = "Devices")]
    [XMLInclude(typeof(Device1))]
    [XMLInclude(typeof(Device2))]
    public class XMLDevicesContainer
    {
    :
    }
    

    【讨论】:

      【解决方案2】:

      如下声明您的XmlSerializer:

      XmlSerializer xs = new XmlSerializer(typeof(obj), extraTypes);
      

      我之前实现的 WCF Web 服务也有同样的问题。我有(object obj) 作为参数,我声明我的XmlSerializer 就像new XmlSerializer(typeof(object)),这在静态上是未知的。 将其更改为new XmlSerializer(obj.GetType()) 即可解决。

      【讨论】:

        猜你喜欢
        • 2010-09-06
        • 2010-12-15
        • 2010-09-07
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        相关资源
        最近更新 更多