2012-12-13 90 views
0

我得到错误“{”类型Device1不是预期的。 。使用XmlInclude或SoapInclude属性来指定不是静态已知类型的 “}”xml序列化和继承类型

目前我有:

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))] 

然后它的工作原理,但我想写多种设备类型的数组。

回答

4

您必须为要在XMLDevicesContainer类中可用的每个子类添加XmlIncludeAttribute。

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

声明你XmlSerializer如下:

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

我有同样的问题与WCF web服务我以前实现。我有(object obj)作为参数&我宣布我的XmlSerializernew XmlSerializer(typeof(object)),这是不知道静态。 更改为new XmlSerializer(obj.GetType())解决了它。