1

I'm still getting to grips with C# and I've been looking for ages to try and find a solution to my problem. (This is a practice project to help me learn C#)

I am able to create and write to a XML Settings file but I'm struggling getting the data from it.

I tried using the top answer from here but it didn't work.

I would like to get both the element and inner text from the XML file and into a 2 columned list (I'm currently using a dictionary and I'm open to change this if I have/need to)

In the first column I'd like the element name, and the second, the inner text.

I would then simply just like to write out the list I've created

XML

<settings>
    <view1>enabled</view1>
    <view2>disabled</view2>
</settings>

C#

private Dictionary<string, string> settingsList = new Dictionary<string, string>();

private void CreateSettings()
{
    XDocument xmlSettings = new XDocument(
        new XElement(
            "settings",
            new XElement("view1", "enabled"),
            new XElement("view2", "disabled")))

    xmlSettings.Save(FilePath);
}

private void ReadSettings
{
    XDocument xmlSettings = XDocument.Load(FilePath);

    //READ XML FROM FILE PATH AND ADD TO LIST
}
Community
  • 1
  • 1
Chris Hall
  • 83
  • 7

2 Answers2

3

You can use ToDictionary method to put your settings into a dictionary:

settingsList = xmlSettings.Descendants().ToDictionary(x => x.Name, x => x.Value);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

Imagine you have the class

public class Setting
{
    public String Name { get; set; }
    public String Value { get; set; }
}

You then would have to do the following to return a list of instances of class Setting

var settings = from node in xmlSettings.Descendants("settings").Descendants()
               select new Setting { Name = node.Name.LocalName, Value = node.Value };
ovm
  • 2,452
  • 3
  • 28
  • 51
  • Is there anyway I can not display the settings element and just the elements within settings? cheers! Both answers work apart from that – Chris Hall Feb 02 '15 at 15:54
  • @ChrisHall you mean in the xml document? No, "XML documents must contain one element that is the parent of all other elements" http://www.w3schools.com/xml/xml_syntax.asp – ovm Feb 02 '15 at 15:58
  • No, I mean what gets returned to the list – Chris Hall Feb 02 '15 at 15:59
  • You are in total control of what you return to that list, but I guess that you are looking for a short and concise key-value-pair generating method, like that one Selman22 posted in their answer. – ovm Feb 02 '15 at 16:02
  • You can do @Chris Hall – Ehsan Sajjad Feb 02 '15 at 16:02
  • @ChrisHall Ehsan Sajjad fixed an error in my answer, which I have edited now. You want the Descendants of the Settings-Node. – ovm Feb 02 '15 at 16:13