Looping through xmlnodes using Xdocument

I have an xml string like this

<Test>
  <ConnectionParameters>
   <ConnectionParameter DisplayName="asd" Id="cgfh" IsPassword="false" IsRequired="true">   </ConnectionParameter>
   <ConnectionParameter DisplayName="asdasd" Id="fgh" IsPassword="false" IsRequired="true"></ConnectionParameter>
    <ConnectionParameter DisplayName="asdasd" Id="hdfh" IsPassword="false" IsRequired="true"></ConnectionParameter>
   <ConnectionParameter DisplayName="asdad" Id="dfgdf" IsPassword="false" IsRequired="true">  </ConnectionParameter>
 </ConnectionParameters>
</Test>

How can I loop through each "ConnectionParameter" tag inorder to get the attributes like Id,DisplayName etc using xdocument?

I tried like this,

 XDocument xdoc = new XDocument();
    xdoc= XDocument.Parse(fileContent);
    var saveResult = from b in xdoc.Descendants("ConnectionParameters")
                     select new
                     {
                         success = (string)b.Element("ConnectionParameter").Attribute("Id").Value ?? string.Empty,
                     };

But it only returns the first node only

Jon Skeet
people
quotationmark

You're currently looping through all the ConnectionParameters elements (of which there's only one) and selecting the first ConnectionParameter element (using the Element call). You want to just loop through the ConnectionParameter elements:

// Note the lack of creating a new XDocument for no reason
XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = from b in xdoc.Descendants("ConnectionParameter")
                 select new
                 {
                     success = (string) b.Attribute("Id") ?? ""
                 };

Or to avoid creating an anonymous type for no obvious reason, and using plain "dot notation" as the query expression isn't helping you much:

XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Descendants("ConnectionParameter")
                     .Select(b => (string) b.Attribute("Id") ?? "");

If you prefer to make the parent element names explicit, you could use:

XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Element("Test")
                     .Element("ConnectionParameters")
                     .Descendants("ConnectionParameter")
                     .Select(b => (string) b.Attribute("Id") ?? "");

Or:

XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Root
                     .Element("ConnectionParameters")
                     .Descendants("ConnectionParameter")
                     .Select(b => (string) b.Attribute("Id") ?? "");

people

See more on this question at Stackoverflow