Reputation: 6562
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;
Upvotes: 0
Views: 2128
Reputation: 236308
You can use XPath:
var folder = XElement.Load(file)
.XPathSelectElements("/settings/add[@key='folder']")
.Select(a => (string)a.Attribute("value"))
.FirstOrDefault();
Upvotes: 1
Reputation: 1503859
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();
Upvotes: 2