3
我想知道在序列化某個基本類型的自定義集合時是否可以定義元素名稱。請看下面的例子(我使用的是這裏的水果例子:)):使用DataContractSerializer時保留集合中的元素名稱
[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>
我真的想要的是一個輸出,其中的水果元素被替換爲他們正確的類名。即:
<Bowl xmlns="http://schemas.datacontract.org/2004/07/">
<Fruits>
<Apple />
<Banana />
</Fruits>
</Bowl>
是否有可能做DataContractSerializer
還是我寫我自己的邏輯,它的XmlWriter?