将XML从url反序列化为C#中的对象

时间:2013-06-01 18:52:48

标签: c# xml-serialization

所以我的网址是xml,如下所示:

<restaurantFoodImpls>
 <RestaurantFood Price="1689.7594" ID="426" Description="quis egreddior glavans brevens, si eggredior. vobis e fecundio, fecundio, et quoque nomen gravum parte volcans">
  <foodItem Name="Frances93" ID="548"/>
  <restaurant Name="Alana59" PhoneNumber="7954016342" MobileNumber="372206-3626" LastName="Hickman" ID="1" FirstName="Gabrielle"/>
 </RestaurantFood>
 <RestaurantFood Price="14.225095" ID="520" Description="in plorum egreddior plorum e pladior in linguens essit. novum habitatio Versus plurissimum volcans linguens estum.">   
  <foodItem Name="Frances93" ID="548"/>
  <restaurant Name="Alana59" PhoneNumber="7954016342" MobileNumber="372206-3626" LastName="Hickman" ID="1" FirstName="Gabrielle"/>
 </RestaurantFood>
</restaurantFoodImpls>

如何使用C#将其解析为对象?
我已经尝试过使用反序列化器,但我的问题是我希望从XML中的属性中读取元素的属性,而我却无法获得它们。

1 个答案:

答案 0 :(得分:2)

var stream = File.Open(filename, FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(RestaurantFoodImpls));
var result = ser.Deserialize(stream) as RestaurantFoodImpls;

public class FoodItem
{
    [XmlAttribute]
    public string Name { get; set; }
    [XmlAttribute]
    public string ID { get; set; }
}

public class Restaurant
{
    [XmlAttribute]
    public string Name { get; set; }
    [XmlAttribute]
    public string PhoneNumber { get; set; }
    [XmlAttribute]
    public string MobileNumber { get; set; }
    [XmlAttribute]
    public string LastName { get; set; }
    [XmlAttribute]
    public string ID { get; set; }
    [XmlAttribute]
    public string FirstName { get; set; }
}

public class RestaurantFood
{
    [XmlAttribute]
    public string Price { get; set; }
    [XmlAttribute]
    public string ID { get; set; }
    [XmlAttribute]
    public string Description { get; set; }
    [XmlElement("foodItem")]
    public FoodItem foodItem { get; set; }
    [XmlElement("restaurant")]
    public Restaurant restaurant { get; set; }
}

[XmlRoot("restaurantFoodImpls")]
public class RestaurantFoodImpls
{
    [XmlElement("RestaurantFood")]
    public List<RestaurantFood> RestaurantFood { get; set; }
}