Tutorial :LINQ to XML return second element


I'm trying to return to the second <link> element in the XML from Flickr.

This always returns the first element:

ImageUrl = item.Element(ns + "link").Attribute("href").Value,  

And this fails?

ImageUrl = item.Elements(ns + "link")[1].Attribute("href").Value,  


Try .Skip(1).First().Attribute.... on the second snippet.


You can use ElementAt to get the element at a specified position in an enumerable:

imageUrl = (string)item.Elements(ns + "link").ElementAt(1).Attribute("href");  


According to the documentation Element returns the first matching child - Elements returns all matching children. To get the second just skip the first item and take the next one.

ImageUrl = item.Elements(ns + "link").Skip(1).First().Attribute("href").Value;  

If you can't be certain there are two children you could do this:

XElement xe = item.Elements(ns + "link").Skip(1).FirstOrDefault();  if(xe != null)  {      ImageUrl = ex.Attribute("href").Value;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »