代码之家  ›  专栏  ›  技术社区  ›  Sergio Tapia

如何获取XML中的所有子元素?

  •  0
  • Sergio Tapia  · 技术社区  · 14 年前

    从这个XML响应: http://www.dreamincode.net/forums/xml.php?showuser=335389

    有人能分享一些XDocument魔法吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Tomas Petricek    14 年前

    <user> 中的元素 <friends> XML文档中的元素,如下所示:

    var url = "http://www.dreamincode.net/forums/xml.php?showuser=335389";
    var doc = XDocument.Load(url);
    var friends = doc.Element("ipb").Element("profile")
                     .Element("friends").Elements("user");
    
    // Or if you don't want to specify the whole path and you know that
    // there is only a single element named <friends>:
    var friends = doc.Descendant("friends").Elements("user");
    

    然后可以使用LINQ处理集合。例如,创建 IEnumerable<string> 有了所有朋友的名字,你可以写:

    var names = from fr in friends 
                select fr.Element("name").Value;
    

    如果你需要唯一的ID,你可以读取 <id> 元素(如果它是整数,也可以使用 Int32.Parse

        2
  •  0
  •   oscarkuo    14 年前