3

我想知道在序列化我的某个基本类型的自定义集合时是否可以定义元素名称。考虑以下示例(我在这里使用水果示例 :)):

[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 或我必须为它编写自己的逻辑?

4

1 回答 1

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);
    }
}
于 2012-11-16T10:15:30.327 回答