2012-11-16 41 views
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?

回答

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); 
    } 
} 
相关问题