tags:

views:

22

answers:

2

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?

A: 

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

oykuo
+2  A: 

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...)

Tomas Petricek