反序列化派生类型

时间:2014-01-30 09:54:32

标签: c# xml

我有一个继承自Base Class的Class Hierarchy。我想从XML反序列化所有类型。文档说使用此构造函数用于此目的:

XmlSerializer(Type type, Type[] extraTypes);

所以我这样做:

public class SomeBase { public string SomeProperty { get; set } }
public class SomeChild : SomeBase { public string SomeOtherProperty { get; set; } }

然后我创建XmlSerializer并尝试反序列化我的XML:

XmlSerializer serializer = new XmlSerializer(typeof(SomeBase),
   new Type[] { typeof(SomeChild) });
SomeBase deserialized = (SomeBase)serializer.Deserialize(new StringReader(myXml));

我得到InvalidOperationException,其中包含:

"<SomeChild xmlns=''> was not expected."

我该如何解决这个问题?

更新 这是我的XML:

// Works fine:
<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<SomeBase>
   <SomeProperty>some value</SomeProperty>
</SomeBase>
// InvalidOperationException:
<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<SomeChild>
   <SomeProperty>some value</SomeProperty>
   <SomeOtherProperty>some other value</SomeOtherProperty>
</SomeChild>

1 个答案:

答案 0 :(得分:0)

您应该指示序列化程序,SomeBase也可以是SomeChild。 您可以使用XmlInclude属性

执行此操作
[XmlInclude(typeof(SomeChild))]
public class SomeBase { public string SomeProperty { get; set } }
public class SomeChild : SomeBase { public string SomeOtherProperty { get; set; } }