2015-01-16 59 views
0

我对XML很陌生。 以下XML被接收为一个字符串从一个web服务将XML转换为ASP.NET MVC模型

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

我试过以下,但值为空;

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

我也按照计算器上的一些答案把XmElement("calculator")等,在性能,但他们也没有工作。

+0

可能重复http://stackoverflow.com/questions/4203540/generate-c-sharp-class-from-xml –

+0

这将帮助:HTTP:/ /stackoverflow.com/questions/26422431/query-xml-file-for-records-using-linq –

+0

什么是问题,什么是不工作 – mybirthname

回答

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

这是有效的。谢谢汤姆! – adiga