如何在xml(XElement)中循环并获取Inside Elements的值

时间:2011-11-27 12:14:30

标签: c# xml linq c#-4.0 linq-to-xml

考虑这个XML:

enter image description here

我将此XML存储在XElemnt。我如何循环投掷Person元素并为每个人获取值ID,Name,LastName

2 个答案:

答案 0 :(得分:2)

var doc = XDocument.Load(<filePath>);
var people = from person in doc.Descendents("Person")
select new Person{
    ID = (int)person.Element("ID"),
    Name = (string)person.Element("Name"),
    LastName = (string)person.Element("LastName");
};

return people.ToList();

答案 1 :(得分:1)

使用XElement,您将获得people变量中的所有人。

XElement d = XElement.Load("D:\\people.xml");
var people = (from p in d.Descendants("Person")
                select new
                {
                    ID = Convert.ToInt32(p.Element("ID").Value),
                    Name = p.Element("Name").Value,
                    LastName = p.Element("LastName").Value
                }).ToList();