我在数据契约上有一个knowntype属性,但不知道如何修改xml以接受这些knowntype

本文关键字:knowntype xml 修改 何修改 契约 数据 有一个 属性 不知道 | 更新日期: 2023-09-27 18:06:10

数据合约示例

[DataContract(Namespace = "namespace")]
[KnownType(typeof(KnownType1))]
public class DataContract
{
    [DataMember(IsRequired = true)]
    public int Value;
}

如何编写xml以使用KnownType1代替DataContract ?我试过这样做:(我忽略了名称空间和所有额外的东西来简化这个例子)

<DataContract> 
      <Value> 1</Value>
      <KnownType1> ....</KnownType>
</DataContract>

我也试过用KnownType1代替DataContract节点,但我认为这也不正确。

我在数据契约上有一个knowntype属性,但不知道如何修改xml以接受这些knowntype

例如,我们有以下dto:

[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;
}

为简单起见(我使用XmlTextWriter(Console.Out)来打印结果xml),序列化函数看起来像:

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);
}

序列化:

[Fact]
public void Test()
{
    Serialize<DataContract>(new KnownType1 { Value = 1, Value1 = 2 });
    Serialize<DataContract>(new DataContract { Value = 1 });
}

结果输出:

<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>

如您所见,KnownType1 xml包含额外的i:type="d1p1:KnownType1"