1

I have a xml file as follows.

Filename:myapp.connfig

<configuration>
  <appSettings>
  <add key="Key1" value="false" />
    <add key="Key2" value="5893893"/>
    <add key="key3" value="44123"/>
  </appSettings>
</configuration>

I want to load this xml file into a datagridview.

I am using Linq to XML but not able to load it.

using Code as below

        var q = from c in xmlDoc.Root.Descendants("configuration").Elements("appSettings")
                select new
                {
                    myKey = c.Element("add").Attributes("key"),
                    myValue = c.Element("add").Attribute("Value").Value

                };

dataGridView1.DataSource = q.ToList();

In the resultset of the query i am getting message as "Empty = "Enumeration yielded no results"".

What is going wrong in above LINQ statement.

Also after loading XML files, I want to edit these values and save back to XML file. How can i accomplish this task.

Thanks in Advance

usr021986
  • 3,421
  • 14
  • 53
  • 64

2 Answers2

2

Xml is case sensitive you should use lowercase names of attributes and elements. Also you have wrong elements selection. configuration is a root of xml, and you are selecting single appSettings element, instead of selecting all add elements inside. Here is how query should look:

var q = from a in xmlDoc.Descendants("appSettings").Elements("add")
        select new
        {
             myKey = (string)a.Attribute("key"), // also here use Attribute
             myValue = (string)a.Attribute("value")
        };
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

xmlDoc.Root already points to configuration element, so you can't query for .Descendants("configuration"), because it will return no elements.

You should also change your elements/attributes names to proper ones - they are case sensitive.

(string)XElement and (string)XAttribute is also better then XElement.Value, because it works fine even when element/attribute was not found. With .Value approach NullReferenceException will be thrown in that situation.

var q = from c in xmlDoc.Root.Elements("appSettings")
        select new
        {
            myKey = (string)c.Element("add").Attribute("key"),
            myValue = (string)c.Element("add").Attribute("value")

        };
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263