Wednesday, January 21, 2015

C# Dictionary to XML

Do you have a string dictionary in .NET code (C#) that want to write out to disk in nicely formatted XML?

A single line of text will do this:

new XElement("root", d.Select(
    kv => new XElement(kv.Key, kv.Value)))
        .Save(filename, SaveOptions.OmitDuplicateNam

To read the XML file back later into a dictionary, is another single line:

var d = XElement.Parse(File.ReadAllText(filename))
    .ToDictionary(k =>
        v => v.Value.ToString

That's it!

No comments: