将XML转换为ASP.NET MVC模型

时间:2015-01-16 07:28:56

标签: c# xml asp.net-mvc

我对XML很新。 以下xml作为来自Web服务

的字符串接收
"<settings>   
  <calculator display="1" />
  <details display="1" />
  <charge display="1" />
  <features>
    <feature code="HAZ" description="CARGO" />
    <feature code="IDL" description="DELIVERY" />
    <feature code="LFT" description="TRUCK" />
    <feature code="NFY" description="CARRIER CHARGE" />
  </addons>
</settings>  "

以下是用户配置,其中列表为属性。

 public class UserConfiguration
 {
     public int calculator { get; set; }

     public int details { get; set; }

     public int charge { get; set; }

     public List<Accessorial> features { get; set; }
 }

 public class Accessorial
 {
     public string code { get; set; }

     public string description { get; set; }
 }

我尝试了以下但是值为null;

XmlSerializer deserializer = new XmlSerializer(typeof(UserConfiguration), new XmlRootAttribute("root"));
var objectValue = deserializer.Deserialize(new StringReader(xml));

我还根据stackoverflow上的一些答案将XmElement("calculator")等放在属性上,但它们也没有用。

1 个答案:

答案 0 :(得分:4)

使用以下与属性编程的合同:

[XmlRoot("settings")]
public class Settings
{
   [XmlElement("calculator")]
   public Calculator calculator { get; set; }

   [XmlArray("features")]
   [XmlArrayItem("feature")]
   public List<Feature> features {get; set; }
}

public class Calculator 
{
    [XmlAttribute]
    public string display { get; set; }
}