简体   繁体   English

如何使用属性和值创建C#MVC模型XML元素

[英]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: 我有一个ac#MVC模型,我想将其序列化为XML文档,如下所示:

<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" 由于Vehicle类别不是属性,因此我需要在该类别中添加一个值,例如“ ford”或“ Toyota”

Right now I have: 现在我有:

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

Add another property with the [XmlText] attribute: 使用[XmlText]属性添加另一个属性:

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

You should also add attributes to your list of Vehicles : 您还应该将属性添加到“ Vehicles列表中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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