codechobo
codechobo

Reputation: 829

Changing inherited class name in XML C#

I am serializing a set of classes that looks like:

public class Wrapper
{
    IInterface obj;
}

public interface IInterface 
{
}

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

Currently the XML generated looks like

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

Is there anyway to include the custom type name as the element name, instead of including it in the type?

Upvotes: 2

Views: 787

Answers (2)

astellin
astellin

Reputation: 443

You should use the 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;
}

This makes the xml serializer aware of the subtypes of IInterface, which the property could hold.

Upvotes: 1

Philip Rieck
Philip Rieck

Reputation: 32568

If you want to do it for this tree, you can put the XmlElementAttribute declaration in your wrapper:

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

Upvotes: 1

Related Questions