我收到错误“{”类型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))]
然后它可以工作,但我想编写多种设备类型的数组。
答案 0 :(得分:4)
您必须为要在XMLDevicesContainer类上使用的每个子类添加XmlIncludeAttribute。
[XmlRoot(ElementName = "Devices")]
[XMLInclude(typeof(Device1))]
[XMLInclude(typeof(Device2))]
public class XMLDevicesContainer
{
:
}
答案 1 :(得分:0)
按如下方式声明您的XmlSerializer
:
XmlSerializer xs = new XmlSerializer(typeof(obj), extraTypes);
我之前实现的WCF Web服务遇到了同样的问题。我有(object obj)
作为参数&amp;我宣布我的XmlSerializer
new XmlSerializer(typeof(object))
就像new XmlSerializer(obj.GetType())
一样,这是静态的。
将其更改为$dateValue = strtotime($q);
$yr = date("Y", $dateValue) ." ";
$mon = date("m", $dateValue)." ";
$date = date("d", $dateValue);
解决了它。