没有XDocument的XML到数组

时间:2014-01-12 01:32:58

标签: c# xml deserialization xml-deserialization

我需要解析XML文档,但我不能使用XDocument。如果不了解为什么我不能使用它的技术细节,我怎么能做到这一点?但是,我可以使用XmlDocument和其他方法。

var restaurants = from r in xdoc.Root.Elements("Restaurant")
                    select new {
                    Name = (string)r.Element("name"),
                    Location = (string)r.Element("location")
                };
foreach(var restaurant in restaurants)
{
    String name = restaurant.Name; 
    String location = restaurant.Location;
}

1 个答案:

答案 0 :(得分:4)

假设XML文件与您在your previous question中描述的文件类似:

<Restaurants>
    <Restaurant>
      <name>test</name>
      <location>test</location>
   </Restaurant>
   <Restaurant>
      <name>test2</name>
      <location>test2</location>
   </Restaurant>
</Restaurants>

是的,我添加了根Restaurants元素,使其成为有效的XML文件。

您可以使用XML反序列化从该XML获取对象:

<强>类

public class Restaurant
{
    [XmlElement(ElementName = "name")]
    public string Name { get; set; }
    [XmlElement(ElementName = "location")]
    public string Location { get; set; }
}

public class Restaurants
{
    [XmlElement(ElementName="Restaurant")]
    public List<Restaurant> Items { get; set; }
}

<强>反序列化

var serializer = new XmlSerializer(typeof(Restaurants));
var restaurants = serializer.Deserialize(File.OpenRead("Input.txt"));