0

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;
2
  • that's not the app.config file for your application is it? Commented Sep 24, 2013 at 19:54
  • it's from another application I need to read for values. Commented Sep 24, 2013 at 19:58

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

You can use XPath:

var folder = XElement.Load(file)
                     .XPathSelectElements("/settings/add[@key='folder']")
                     .Select(a => (string)a.Attribute("value"))
                     .FirstOrDefault();

1 Comment

much better than the chosen answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.