Reputation: 317
Example Datacontract
[DataContract(Namespace = "namespace")]
[KnownType(typeof(KnownType1))]
public class DataContract
{
[DataMember(IsRequired = true)]
public int Value;
}
How do I write the xml to make use of KnownType1 in place of DataContract. I've tried doing: (I've ignored namespaces and all the extra stuff to simplify this example)
<DataContract>
<Value> 1</Value>
<KnownType1> ....</KnownType>
</DataContract>
I've also tried replace the DataContract node with KnownType1 but I don't think that is correct either.
Upvotes: 0
Views: 797
Reputation: 4778
For example, we've following DTOs:
[DataContract(Namespace = "namespace")]
[KnownType(typeof(KnownType1))]
public class DataContract
{
[DataMember(IsRequired = true)]
public int Value;
}
[DataContract(Namespace = "namespace1")]
public sealed class KnownType1 : DataContract
{
[DataMember(IsRequired = true)]
public int Value1;
}
for simplicity (I've used XmlTextWriter(Console.Out)
to print result xml) , serialization function looks like:
private void Serialize<T>(object value)
{
XmlObjectSerializer serializer = new DataContractSerializer(typeof(T));
var writer = new XmlTextWriter(Console.Out)
{
Formatting = Formatting.Indented
};
serializer.WriteObject(writer, value);
}
Here's serialization:
[Fact]
public void Test()
{
Serialize<DataContract>(new KnownType1 { Value = 1, Value1 = 2 });
Serialize<DataContract>(new DataContract { Value = 1 });
}
The result output:
<DataContract xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d1p1="namespace1" i:type="d1p1:KnownType1" xmlns="namespace">
<Value>1</Value>
<d1p1:Value1>2</d1p1:Value1>
</DataContract>
<DataContract xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="namespace">
<Value>1</Value>
</DataContract>
As you see, KnownType1
xml contains additional i:type="d1p1:KnownType1"
Upvotes: 1