Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取XML中的所有子元素?_C#_.net_Linq To Xml - Fatal编程技术网

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

C# 如何获取XML中的所有子元素?,c#,.net,linq-to-xml,C#,.net,Linq To Xml,从这个XML响应中: 我想抓住所有的用户朋友。我需要从朋友那里获取所有信息。通常在我得到帮助的情况下,我会使用唯一的ID来抓取每个用户,但是由于每个用户没有相同的朋友,所以它必须是动态的,我不能硬编码任何东西 有人愿意分享一些XDocument魔法吗?您可能可以使用XPath查询 示例使用JScript,但.NET也支持它。您可以从XML文档中获取元素中的所有元素,如下所示: var url = "http://www.dreamincode.net/forums/xml.php?showus

从这个XML响应中:

我想抓住所有的用户朋友。我需要从朋友那里获取所有信息。通常在我得到帮助的情况下,我会使用唯一的ID来抓取每个用户,但是由于每个用户没有相同的朋友,所以它必须是动态的,我不能硬编码任何东西


有人愿意分享一些XDocument魔法吗?

您可能可以使用XPath查询

示例使用JScript,但.NET也支持它。您可以从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");
如果您需要唯一的ID,您可以以类似的方式读取
元素(如果它是整数,您也可以使用
Int32.parse
解析它,例如…)

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