我想知道在序列化我的某个基本类型的自定义集合时是否可以定义元素名称。考虑以下示例(我在这里使用水果示例 :)):
[DataContract(Name = "Bowl")]
public class Bowl
{
[DataMember]
public List<Fruit> Fruits { get; set; }
}
[DataContract(Name = "Fruit")]
public abstract class Fruit
{
}
[DataContract(Name = "Apple", Namespace = "")]
public class Apple : Fruit
{
}
[DataContract(Name = "Banana", Namespace = "")]
public class Banana : Fruit
{
}
序列化时:
var bowl = new Bowl() { Fruits = new List<Fruit> { new Apple(), new Banana() } };
var serializer = new DataContractSerializer(typeof(Bowl), new[] { typeof(Apple), typeof(Banana) });
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, bowl);
ms.Position = 0;
Console.WriteLine(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
}
会给我一个输出:
<Bowl xmlns="http://schemas.datacontract.org/2004/07/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Fruits>
<Fruit i:type="Apple" xmlns="" />
<Fruit i:type="Banana" xmlns="" />
</Fruits>
</Bowl>
我真正想要的是一个输出,其中 Fruit 元素被替换为它们的正确类名。IE:
<Bowl xmlns="http://schemas.datacontract.org/2004/07/">
<Fruits>
<Apple />
<Banana />
</Fruits>
</Bowl>
是否可以DataContractSerializer
使用 XmlWriter 或我必须为它编写自己的逻辑?