如何获取 XML 中的所有子元素?
来自此 XML 响应: http://www.dreamincode.net/forums/xml .php?showuser=335389
我想抓取所有用户好友。我需要从朋友那里获取所有信息。通常,在我得到的帮助下,我会使用唯一的 ID 来获取每个用户,但由于每个用户没有相同的朋友,因此它必须是动态的,而且我无法对任何内容进行硬编码。
有人可以分享一些 XDocument 的魔法吗?
From this XML response: http://www.dreamincode.net/forums/xml.php?showuser=335389
I want to grab all of the users friends. I need to grab all of the information from the friends. Usually with the help I've been given I would use the unique ID to grab each, but since each users doesn't have the same friends it has to be dynamic and I can't hard code anything.
Would anyone please share some XDocument magic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样从 XML 文档中获取
元素中的所有
元素:然后您可以使用 LINQ 来处理该集合。例如,要创建包含所有朋友名称的
IEnumerable
,您可以编写:如果您需要唯一 ID,则可以读取
元素以类似的方式(如果它是一个整数,您也可以使用Int32.Parse
来解析它,例如......)You can get all
<user>
elements in the<friends>
element from the XML document like this:Then you can use LINQ to process the collection. For example, to create a
IEnumerable<string>
with the names of all frineds, you could write:If you needed unique ID, you could read the
<id>
element in a similar way (if it is an integer, you could also parse it usingInt32.Parse
for example...)您可以使用 XPath 查询
http://www.w3schools.com/xpath/xpath_examples.asp< /a>
示例使用 JScript,但 .NET 也支持它
you can probably use XPath query
http://www.w3schools.com/xpath/xpath_examples.asp
the examples uses JScript but it is also supported in .NET