简体   繁体   中英

How to create C# MVC model XML element with attribute and value

I have ac# MVC model which I would like to serialize to an XML document to look like this:

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

Here is the model:

[Serializable]
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; }
}

Since class Vehicle is not a property what do I need to add to the class to give it a value of for example "ford" or "Toyota"

Right now I have:

var myvehicle = new Vehicle {color = "red", speed = "50mph"};

Add another property with the [XmlText] attribute:

[XmlText]
public string Make {get; set;}

You should also add attributes to your list of Vehicles :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM