2010-10-06 67 views
2

我序列化一组看起来像类:改变XML C#继承的类名

public class Wrapper 
{ 
    IInterface obj; 
} 

public interface IInterface 
{ 
} 

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

目前,XML产生的样子

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

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

+1

我怀疑答案是编写你自己的序列化程序。 – Lazarus 2010-10-06 13:58:51

回答

1

如果你想这样做的这棵树,你可以把XmlElementAttribute声明在您的包装:

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

这将使用元素名称ClassA来实现IInterface的任何实现。我相信OP正在寻找一些只会使用ClassA作为ImplA类的元素名的东西。 – 2010-10-06 14:05:18

+0

没错,界面会有多种实现。 – codechobo 2010-10-06 14:06:29

+0

@codechobo - 但是你想要每个实现具有相同的元素名称,或者每个实现具有不同的元素名称(这会给它们所有相同的元素名称)。 – 2010-10-06 14:10:28

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的子类型,属性可以容纳。