【问题标题】:How to loop through a set of XElements?如何遍历一组 XElement?
【发布时间】:2010-10-25 23:00:58
【问题描述】:

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

鉴于上面的 XML,如果每个子组都相同但值不同,我如何遍历“lastvisitors”元素内的每个元素?

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

所以现在我已经捕获了包含我需要的所有内容的 XElement。有没有办法循环遍历元素以获得我需要的东西?

我有一个名为 Visitor 的 POCO 对象,其唯一目的是保存必要的信息。

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; }
    }
}

再次感谢您的帮助。

【问题讨论】:

    标签: c# xml linq-to-xml xelement


    【解决方案1】:

    你也许可以在 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
                    });
    

    这里唯一需要注意的是,我没有进行任何空值检查。

    【讨论】:

      【解决方案2】:

      只需执行 linq 查询以选择所有元素作为您的对象。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 2010-10-04
        相关资源
        最近更新 更多