Reading XML nested node values

Having an issue grabbing values in an XML file The structure is as followed

<configuration>
    <settings>
       <add key="folder" value = "c:\...." />
    </settings>
</configuration>

i want to be able to read the value from folder.

string val = string.Empty;

        foreach (XElement element in XElement.Load(file).Elements("configuration"))
        {
            foreach (XElement element2 in element.Elements("settings"))
            {
                if (element2.Name.Equals("folder"))
                {
                    val = element2.Attribute(key).Value;
                    break;
                }
            }
        }

        return val;
Jon Skeet
people
quotationmark

The name of the element isn't folder... that's the value of the key attribute. Also note that as you've used XElement.Load, the element is the configuration element - asking for Elements("configuration") will give you an empty collection. You could either load an XDocument instead, or just assume you're on a configuration element and look beneath it for settings.

I think you want:

return XElement.Load(file)
               .Elements("settings")
               .Elements("add")
               .Where(x => (string) x.Attribute("key") == "folder")
               .Select(x => (string) x.Attribute("value"))
               .FirstOrDefault();

people

See more on this question at Stackoverflow