开发者

How to loop through a set of XElements?

开发者 https://www.devze.com 2023-01-22 03:45 出处:网络
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 w

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 Sys开发者_开发技巧tem;
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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消