1

How can I place collection of same elemets under parent element when serialezed:

Serialization produces the following:

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

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

Instead of:

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

I serialize using:

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();

I tried something like this which generated errors:

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

1 回答 1

2

假设你的意思是你想要

<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; }
于 2013-08-27T21:58:32.240 回答