2015-01-16 93 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