简体   繁体   中英

I have a knowntype attribute on a datacontract and don't know how to modify xml to accept these knowntypes

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM