[英]xml serialization and Inherited Types
I got the error "{"The type Device1 was not expected. 我收到错误“ {”。Device1类型未预期。 Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}"
使用XmlInclude或SoapInclude属性可以指定静态未知的类型。“}”
Currently I have: 目前我有:
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;
}
}
}
and i am doing: 我正在做:
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) });
serializer does: 序列化程序可以:
public static void Serialize<T>(T obj, XmlWriter writer, Type[] extraTypes)
{
XmlSerializer xs = new XmlSerializer(typeof(T), extraTypes);
xs.Serialize(writer, obj);
}
I fall on the last line in the serializer method (xs.Serialize) on the error: "{"The type Device1 was not expected. 我在以下错误的序列化器方法(xs.Serialize)的最后一行:“ {”类型Device1不是所期望的。 Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}"
使用XmlInclude或SoapInclude属性可以指定静态未知的类型。“}”
I tried to write XmlInclude on the Device class. 我试图在Device类上编写XmlInclude。 not helped.
没有帮助。 If I change the line
如果我换线
[XmlArrayItem("Device", typeof(Device))]
to be 成为
[XmlArrayItem("Device", typeof(Device1))]
then it works, but I want to write array of multiple Device types. 然后就可以了,但是我想写多个设备类型的数组。
You must add the XmlIncludeAttribute for each subclass you want to be available on the XMLDevicesContainer class. 您必须为要在XMLDevicesContainer类上可用的每个子类添加XmlIncludeAttribute。
[XmlRoot(ElementName = "Devices")]
[XMLInclude(typeof(Device1))]
[XMLInclude(typeof(Device2))]
public class XMLDevicesContainer
{
:
}
Declare your XmlSerializer
as follows: 声明您的
XmlSerializer
,如下所示:
XmlSerializer xs = new XmlSerializer(typeof(obj), extraTypes);
I had the same problem with a WCF webservice i implemented previously. 我以前实现的WCF Web服务也有同样的问题。 I had
(object obj)
as a parameter & I was declaring my XmlSerializer
like new XmlSerializer(typeof(object))
, which wasn't known statically. 我有
(object obj)
作为参数,并且我像new XmlSerializer(typeof(object))
一样声明了XmlSerializer
,它不是静态已知的。 Changing it to new XmlSerializer(obj.GetType())
solved it. 将其更改为
new XmlSerializer(obj.GetType())
解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.