Search code examples
c#xmllinq-to-xmlxelement

How to loop through a set of XElements?


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.


Solution

  • 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.