How to loop through a set of XElements?

10,952

Solution 1

You can probably just do something like this in Linq:

XDocument xml = XDocument.Parse(xmlString);
var visitors = (from visitor in xml.Descendants("latestvisitors").Descendants("user")
                select new Visitor() {
                  ID = visitor.Element("id").Value,
                  Name = visitor.Element("name").Value,
                  Url = visitor.Element("url").Value,
                  Photo = visitor.Element("photo").Value,
                  Visited = visitor.Element("visited").Value
                });

The only caveat here is that I didn't do any null checking.

Solution 2

Just do a linq query to select all the elements as your object.

var visitors = (from v in xml.Element("ipb").Element("profile")
                             .Element("latestvisitors").Elements()
               select new Visitor {
                   ID = (string)v.Element("id"),
                   Name = (string)v.Element("name"),

               }).ToList();
Share:
10,952
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    http://www.dreamincode.net/forums/xml.php?showuser=335389

    Given the XML above, how can I iterate through each element inside of the 'lastvisitors' element, given that each child group is the same with just different values?

    //Load latest visitors.
    var visitorXML = xml.Element("ipb").Element("profile").Element("latestvisitors");
    

    So now I have captured the XElement containing everything I need. Is there a way to loop through the elements to get what I need?

    I have this POCO object called Visitor whose only purpose is to hold the necesary information.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SharpDIC.Entities
    {
        public class Visitor
        {
            public string ID { get; set; }
            public string Name { get; set; }
            public string Url { get; set; }
            public string Photo { get; set; }
            public string Visited { get; set; }
        }
    }
    

    Thanks again for the help.