考虑这个XML:
我将此XML
存储在XElemnt
。我如何循环投掷Person
元素并为每个人获取值ID,Name,LastName
?
答案 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();