views:

58

answers:

2

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?

+1  A: 

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;
}
Philip Rieck
This will use the element name ClassA for any implementation of IInterface. I believe the OP is looking for something that will only use ClassA as an element name for the class ImplA.
Justin Niessner
That's right, there would be multiple implementation for the interface.
codechobo
@codechobo - But would you want each implementation to have the same element name or each implementation have a different element name (this would give them all the same element name).
Justin Niessner
Different element names, so I think the names would have to be defined within the inherited classes
codechobo
@Justin Niessner Ah, I see what you're saying. Yes, this would make the element named "ClassA" for all implementations.
Philip Rieck
A: 

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.

Excel20