score:2

Accepted answer

You need to use root.Descendants instead of root.Elements.

For example,

IEnumerable<XElement> xElements =   from element in root.Descendants("TestDriveRequest")
                where element.Attribute("Record").Value == "1"
                select element;

XContainer.Elements

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.

XContainer.Descendants

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 Output

Complete Code

IEnumerable<XElement> xElements =   from element in root.Descendants("TestDriveRequest")
            where element.Attribute("Record").Value == "1"
            select element;

foreach (XElement el in xElements.Descendants().Where(p => !p.HasElements))
{
   int keyInt = 0;
   string keyName = el.Attribute("name").Value;

   while (keyValuePairs.ContainsKey(keyName))
   {
     keyName = $"{el.Attribute("name").Value}_{keyInt++}";
   }
   keyValuePairs.Add(keyName, el.Value);
}  

Sample Output

enter image description here

score:0

This is how I would create the dictionary :

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace AscendingSequences
{
    class AscendingSequences
    {
        const string FILENAME = @"c:\temp\test.xml";
        public static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<int, Dictionary<string, string>> dict = doc.Descendants("TestDriveRequest")
                .GroupBy(x => (int)x.Attribute("Record"), y => y.Elements("element")
                    .GroupBy(a => (string)a.Attribute("name"), b => (string)b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}

Related Articles