2013-08-27 15 views
1

如何可以将父元素之下相同elemets的集合下元件serialezed时:如何构建对象序列化等相同的父

序列化产生以下:

<Vehicle> 
    <Type color="red" speed="50mph">Ford</Type> 
</Vehicle> 

<Vehicle> 
    <Type color="blue" speed="70mph">Toyota</Type> 
</Vehicle> 

代替:

<Vehicle> 
    <Type color="red" speed="50mph">Ford</Type> 
    <Type color="blue" speed="70mph">Toyota</Type> 
</Vehicle> 

Here is my model: 

[Serializable] 
[XmlRoot("Vehicle")] 
public class Production 
{ 
    public List<Vehicle> Vehicles { get; set; } 
} 

[Serializable] 
public class Vehicle 
{ 
    [XmlAttribute] 
    public string color { get; set; } 

    [XmlAttribute] 
    public string speed { get; set; } 
} 

序列化使用:

System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Prodcution)); 
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Vehicles.xml"); 
writer.Serialize(file, Vehicle); 
file.Close(); 

我想是这样的,其产生的错误:

[XmlArray("Vehicle")] 
ArrayItem("Vehicles")] 
public List<Vehicle> Vehicles { get; set; } 
+1

有没有你想的理由做这个?你试图做的事情基本上意味着1辆车可以同时拥有两种类型。假设你有这个XML,在这种情况下反序列化的对象将如何看起来像? – PoweredByOrange

+0

我正在将XML发送给第三方应用程序,并以这种方式解析数据 – Milligran

回答

2

假设你的意思是你想

<Vehicles> 
    <Vehicle> 
     <Type color="red" speed="50mph">Ford</Type> 
    </Vehicle> 

    <Vehicle> 
     <Type color="blue" speed="70mph">Toyota</Type> 
    </Vehicle> 
</Vehicles> 

你几乎有它see MSDN

[XmlArray("Vehicles")] 
public List<Vehicle> Vehicles { get; set; } 
相关问题