Question

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.

Was it helpful?

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.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top