[英]How to force XML deserialization to derived types of the same name?
I have types provided in a library I cant modify, such as this: 我在库中提供的类型我无法修改,例如:
namespace BaseNamespace
{
public class A
{
public string Foo { get; set; }
}
}
I also have a class named SomeOtherNamespace.A" that derives from BaseNamespace.A like this: 我还有一个名为SomeOtherNamespace.A的类,它从BaseNamespace.A派生,如下所示:
namespace SomeOtherNamespace
{
public class A : BaseNamespace.A
{
public string DoSomething() {}
}
}
From a web service I receive an XML payload with in it. 从Web服务中,我收到了一个XML有效负载。
I want to deserialize the XML so that I end up with a SomeOtherNamespace.A object. 我想反序列化XML,以便最终得到SomeOtherNamespace.A对象。 However when I run the following code
但是当我运行以下代码时
string xml = "<A Foo=\"test\"></A>";
XmlSerializer serializer = new XmlSerializer(typeof(A));
StringReader reader = new StringReader(xml);
A obj = serializer.Deserialize(reader) as A;
I get an error: 我收到一个错误:
Types 'BaseNamespace.A' and 'SomeOtherNamespace.A' both use the XML type name, 'A', from namespace ''.
类型'BaseNamespace.A'和'SomeOtherNamespace.A'都使用来自命名空间''的XML类型名称'A'。 Use XML attributes to specify a unique XML name and/or namespace for the type.
使用XML属性为类型指定唯一的XML名称和/或命名空间。
Question : Without modification of the class BaseNamespace.A how can I force deserialization to my derived type SomeOtherNamespace.A? 问题 :如果不修改类BaseNamespace.A,如何强制反序列化到派生类型SomeOtherNamespace.A?
Rename your SomeOtherNamespace.A
as 将
SomeOtherNamespace.A
重命名为
namespace SomeOtherNamespace
{
public class AAA : BaseNamespace.A
{
public string DoSomething() {}
}
} }
and create serializer as 并创建序列化器
XmlRootAttribute root = new XmlRootAttribute("A");
XmlSerializer serializer = new XmlSerializer(typeof(AAA),root);
If it is acceptable to use a different name in Xml for SomeOtherNamespace.A, you can just use XmlTypeAttribute to give A a different Xml type. 如果可以在Xml中为SomeOtherNamespace.A使用不同的名称,则可以使用XmlTypeAttribute为A提供不同的Xml类型。
namespace SomeOtherNamespace {
[XmlType("NotA")]
public class A
{
public string Foo { get; set; }
}
}
More importantly, you may want to consider a design in which your derived class does not have the same name as the base class. 更重要的是,您可能需要考虑一种设计,其中派生类与基类的名称不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.