Get attributes Name and Value of element in C# through System.Linq

c#, linq, linq-to-xml, xml

Solution

If you want to use this Xml Library you can get all the students and their details with this code:

XElement root = XElement.Load(file); // or .Parse(string)
var students = root.Elements("student").Select(s => new
{
    Name = s.Get("Detail/Name", string.Empty),
    Class = s.Get("Detail/Class", string.Empty),
    Items = s.GetElements("Detail/add").Select(add => new
    {
        Key = add.Get("key", string.Empty),
        Value = add.Get("value", string.Empty)
    }).ToArray()
}).ToArray();

Then to iterate over them use:

foreach(var student in students)
{
    Console.WriteLine(string.Format("{0}: {1}", student.Name, student.Class));
    foreach(var item in student.Items)
        Console.WriteLine(string.Format("  Key: {0}, Value: {1}", item.Key, item.Value));
}

Problem

I have one custom config file. ``` <Students> <student> <Detail Name="abc" Class="1st Year"> <add key="Main" value="web"/> <add key="Optional" value="database"/> </Detail> </student> </Students> ``` I read this file through the IConfigurationHandler interface implementation. When I read the childNode attributes of Detail element. It return me below result into Immediate Window of IDE. ``` elem.Attributes.ToObjectArray() {object[2]} [0]: {Attribute, Name="key", Value="Main"} [1]: {Attribute, Name="value", Value="web"} ``` When I try to write on Console ``` Console.WriteLine("Value '{0}'",elem.Attributes.ToObjectArray()); ``` it does return me ``` Value : 'System.Configuration.ConfigXmlAttribute' ``` `elem.Attributes.Item(1)` method gives me the Name and Value detail but here I need to pass the index value of attribute which I don't know currently. I want to get Name and value of attribute through LINQ query and individual display on Console for each childNode attribute as follows: ``` Value : Name="Key" and Value="Main" Name="value", Value="web" ``` How can I achieve that?

Original source