Can't loop children of returned XML Nodes in C#

I have a large, messy XML file and I want to retrieve ALL elements of the same name ("Item" for the sake of this post) from it, then be able to retrieve data from each element's children.

So far I have returned a list of every element called "Item" using this code, which just displays the namespace url and "Item" in p tags:

XDocument doc = XDocument.Load(@"C:\inetpub\wwwroot\mysite\myxml.xml");
XNamespace ns = "http://www.mynamespace.com";
var nodes = doc.Descendants().Elements(ns + "Item").Select(d => d.Name).ToList();

foreach(var x in nodes){
    <p>@x</p>
}

However, by amending the code with the following, I can't retrieve any data of it's children and I get the error 'System.Xml.Linq.XName' does not contain a definition for 'Descendants':

foreach(var x in nodes){
    <p>@x.Descendants().Element("Name")</p>
}

Here is a very basic version of my XML file:

<Item>
    <Name>Item 1</Name>
    <Type>Type 1</Type>
</Item>

I want to be able to search each 'Item' element for a 'Name' element and return the value. Can anyone see where I'm going wrong?

Jon Skeet
people
quotationmark

This is the problem:

.Select(d => d.Name)

You're explicitly selecting the names of the elements. If you want the actual elements (which I think you do), just get rid of that call:

var nodes = doc.Descendants().Elements(ns + "Item").ToList();

You could also get rid of the ToList() unless you need the query to be materialized eagerly.

people

See more on this question at Stackoverflow