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

本文关键字:元素 对象 何构造 序列化 | 更新日期: 2023-09-27 18:29:11

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

序列化生成以下内容:

<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; }

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

假设您想要

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

你几乎看到了MSDN

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