Tutorial :LINQ to XML return second element



Question:

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,  


Solution:1

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


Solution:2

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


Solution:3

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
Previous
Next Post »