C# c#lingxml 27/02/2016

Read XML file with LINQ to XML in C#

Example:

using System.Xml.Linq;
...
var options = XDocument.Load(@"Options.xml")
    .Root
    .Element("OptionList")
    .Elements("Option")
    .Select(o => new {
        Key = (string)o.Attribute("Name"),
        Value = (string)o.Attribute("Value")
    })
    .ToDictionary(
        o => o.Key,
        o => o.Value
    );

The snippet above reads options from a XML file (Options.xml) into a dictionary object:

<?xml version="1.0" encoding="utf-8"?>
<Application>
  <OptionList>
    <Option Name="ConnectTimeout" Value="5" />
    <Option Name="RetryCount" Value="3" />
  </OptionList>
</Application>