如何构造对象以在同一父级下序列化相似的元素

时间:2013-08-27 21:54:25

标签: c# asp.net-mvc

如何在串行化时将相同元素的集合放在父元素下:

序列化产生以下内容:

<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 个答案:

答案 0 :(得分: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; }