使用DataContractSerializer时保留集合中的元素名称

时间:2012-11-16 07:59:41

标签: c# xml 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>

我真正想要的是一个输出,其中Fruit元素将替换为正确的类名。即:

<Bowl xmlns="http://schemas.datacontract.org/2004/07/">
  <Fruits>
    <Apple />
    <Banana />
  </Fruits>
</Bowl>

是否可以使用DataContractSerializer或者我是否必须使用XmlWriter为其编写自己的逻辑?

1 个答案:

答案 0 :(得分:3)

如果您想要对xml输出进行大量控制,则应该为XmlSerializer注释,而不是DataContractSerializer。例如:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Bowl {
    [XmlArray("Fruits")]
    [XmlArrayItem("Apple", typeof(Apple))]
    [XmlArrayItem("Banana", typeof(Banana))]
    public List<Fruit> Fruits { get; set; }
}
public abstract class Fruit { }
public class Apple : Fruit { }
public class Banana : Fruit { }

static class Program {
    static void Main() {
        var ser = new XmlSerializer(typeof(Bowl));
        var obj = new Bowl {
            Fruits = new List<Fruit> {
                new Apple(), new Banana()
            }
        };
        ser.Serialize(Console.Out, obj);
    }
}