开发者

How can I grab all the child elements in XML?

开发者 https://www.devze.com 2023-01-05 15:19 出处:网络
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 hel

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 us开发者_运维知识库ers 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?


You can get all <user> elements in the <friends> element from the XML document like this:

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

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:

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

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 using Int32.Parse for example...)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消