0

I'm trying to serialize below class using the SoapCore and DataContractSerializer the way the property that holds object (TestProperty) is omitted in the soap message and the element name defines its type name (SomeType in this example)

[DataContract]
[KnownType(typeof(SomeType))]
[KnownType(typeof(SomeType1))]
[KnownType(typeof(SomeType2))]
public class TestClass {
   public string Prop1 {get;set;}   
   public string Prop2 {get;set;}
[DataMember]
   public object TestProperty { get;set; }
}

The desired output would look like this:

<TestClass xmlns="...">
   <Prop1>test</Prop1>
   <Prop2>test</Prop2>
   <SomeType></SomeType>
</TestClass>

..instead of what the DataContractSerializer produces now:

<TestClass xmlns="...">
   <Prop1>test</Prop1>
   <Prop2>test</Prop2>
   <TestProperty i:type="SomeType">...</TestProperty>
</TestClass>

Is there a way to achieve this? I need this in order to keep compatibility with a system written in c++, which expects the element and its type to be declared as a element having type as name instead of using i:type attribute.

dbc
  • 104,963
  • 20
  • 228
  • 340
A.D.
  • 425
  • 3
  • 15
  • Not without implementing `IXmlSerializable`. `XmlSerializer` supports polymorphism by element name as well as by `xsi:type`, see [Using XmlSerializer to serialize derived classes](https://stackoverflow.com/a/1643424/3744182). `DataContractSerializer` only supports the latter. – dbc Dec 10 '21 at 21:18
  • See e.g. [How can you remove the type attribute from a KnownType in a DataContract class?](https://stackoverflow.com/q/48533107/3744182) or [Can I 'override' Name for DataMember in Derived class?](https://stackoverflow.com/q/55881454/3744182) both of which are unanswered. See also [Serialize a list of objects inheriting from class A to xml, so the names of the elements in the xml are B,C,D](https://stackoverflow.com/q/50471935/3744182) whose answer proposes switching to `XmlSerializer` as a workaround. – dbc Dec 10 '21 at 21:20

0 Answers0