DooDoo
DooDoo

Reputation: 13487

how to loop in xml (XElement) and get values od Inside Elements

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?

Upvotes: 1

Views: 6446

Answers (2)

Zain Shaikh
Zain Shaikh

Reputation: 6043

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();

Upvotes: 1

ek_ny
ek_ny

Reputation: 10243

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();

Upvotes: 2

Related Questions