在XML C#中更改继承的类名

时间:2010-10-06 13:55:07

标签: c# xml-serialization xsd

我正在序列化一组看起来像这样的类:

public class Wrapper
{
    IInterface obj;
}

public interface IInterface 
{
}

[XmlType("ClassA")]
public ImplA : IInterface 
{
}

目前生成的XML看起来像

<Wrapper>
   <IInterface xsi:type="ClassA">
...
   </IInterface>
</Wrapper>

是否有自定义类型名称作为元素名称,而不是将其包含在类型中?

2 个答案:

答案 0 :(得分:1)

如果要对此树执行此操作,可以将XmlElementAttribute声明放在包装器中:

public class Wrapper
{
    [XmlElement(ElementName="ClassA")]
    IInterface obj;
}

答案 1 :(得分:1)

您应该使用XmlIncludeAttribute:

public class Wrapper
{
    //XmlInclude should in this case at least include ImplA, but you propably want all other subclasses/implementations of IInterface
    [XmlInclude(typeof(ImplA)), XmlInclude(typeof(ImplB))]
    IInterface obj;
}

这使得xml序列化程序能够识别属性可以容纳的IInterface的子类型。