LINQ to XML - Elements() works but Elements(XName) does not work

You need to take the namespace into account:

XNamespace df = data.Root.Name.Namespace;

Then use df + "foo" to select elements with local name foo in the namespace defined on the root element.

And as already mentioned you probably want to select descendants, not child elements:

        var elements = from c in data.Descendants(df + "Textbox")
                       select c;

You are looking for Descendants() not Elements() in this case. Elements() only selects immediate children.

Documentation

  • XContainer.Descendants Method (XName) - Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection
  • XContainer.Elements Method (XName) - Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching XName are included in the collection.

Note: Based on your sample code, using Descendants() will still throw an exception because not all of the ReportItems elements have a Name attribute. You need to do something like Console.WriteLine("Element : " + (element.Attributes("Name").Any() ? element.Attribute("Name").Value : "(no name)") );