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?

codechobo
  • 829
  • 1
  • 7
  • 12

2 Answers2

1

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
  • 32,368
  • 11
  • 87
  • 99
  • 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 Oct 06 '10 at 14:05
  • That's right, there would be multiple implementation for the interface. – codechobo Oct 06 '10 at 14:06
  • @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 Oct 06 '10 at 14:10
  • Different element names, so I think the names would have to be defined within the inherited classes – codechobo Oct 06 '10 at 14:14
  • @Justin Niessner Ah, I see what you're saying. Yes, this would make the element named "ClassA" for all implementations. – Philip Rieck Oct 06 '10 at 14:32
1

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.

astellin
  • 433
  • 3
  • 13