C# 如何获取XML中的所有子元素?
从这个XML响应中: 我想抓住所有的用户朋友。我需要从朋友那里获取所有信息。通常在我得到帮助的情况下,我会使用唯一的ID来抓取每个用户,但是由于每个用户没有相同的朋友,所以它必须是动态的,我不能硬编码任何东西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
有人愿意分享一些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;