Getting wrong information when scraping XML with Linq
Image I have this XML:
<ipb>
<profile>
<id>335389</id>
<name>stapia.gutierrez</name>开发者_开发百科
<rating>0</rating>
</profile>
</ipb>
I'm trying to get ID, Name and Rating. Any guidance?
Here's what I have and what I receive:
public User FindInformation()
{
string xml = new WebClient().DownloadString(String.Format("http://www.dreamincode.net/forums/xml.php?showuser={0}", userID));
XDocument doc = XDocument.Parse(xml);
var id = from u in doc.Descendants("profile")
select (string)u.Element("id");
var name = from u in doc.Descendants("profile")
select (string)u.Element("name");
var rating = from u in doc.Descendants("profile")
select (string)u.Element("rating");
User user = new User();
user.ID = id.ToString();
user.Name = name.ToString();
user.Rating = rating.ToString();
return user;
}
This is what I get in my TextBox for testing purposes.
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]
You need to extract a single instance of <profile>
and then operate on that:
XDocument doc = XDocument.Parse(xml);
foreach(var profile in doc.Descendants("profile"))
{
var id = profile.Element("id").Value;
var name = profile.Element("name").Value;
var rating = profile.Element("rating").Value;
User user = new User();
user.ID = id;
user.Name = name;
user.Rating = rating;
}
What you're doing now is selecting a list of nodes (doc.Descendants("profile")
will return a list of nodes, possibly with just one element - but still a list), and then all the "id" elements from within that list.... not really what you want, I guess!
var id = from u in doc.Descendants("profile")
select (string)u.Element("id");
This & other statements like these will return you an enumerable & not a specific instance. i.e what happens, if your xml has many nodes that satisfy the condition?
So, if you are looking to get the first item (or if you have a xml structure exactly as shown above with no extra nodes), a call to First
or FirstOrDefault
should help.
精彩评论