1

Consider this XML:

enter image description here

I store this XML in XElemnt.How I can loop throw Person elements and get value ID,Name,LastName for each person?

Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

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();
ek_ny
  • 10,153
  • 6
  • 47
  • 60
  • I'm using XElement.please say how to use XElement with your sample – Arian Nov 27 '11 at 12:25
  • 1
    you could replace doc with your XElement, I suppose. XElement has a Load method as well. http://msdn.microsoft.com/en-us/library/bb298435.aspx – ek_ny Nov 27 '11 at 12:28
1

using XElement, you will get all the people in people variable.

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();
Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66