Back to all posts
C#.NETXML

How to Load XML File and Convert to Dictionary

SathishMarch 8, 2010

Converting XML to Dictionary is useful when you need key-value pair access to XML data.

XML to Dictionary

csharp
using System.Xml.Linq;
using System.Collections.Generic;

public static Dictionary<string, string> XmlToDictionary(string xmlPath)
{
    XDocument doc = XDocument.Load(xmlPath);
    
    return doc.Root.Elements()
        .ToDictionary(
            e => e.Name.LocalName,
            e => e.Value
        );
}

// Usage
var dict = XmlToDictionary("config.xml");
string value = dict["SettingName"];

Handling Nested XML

csharp
public static Dictionary<string, string> FlattenXml(XElement element, string prefix = "")
{
    var result = new Dictionary<string, string>();
    
    foreach (var child in element.Elements())
    {
        string key = string.IsNullOrEmpty(prefix) 
            ? child.Name.LocalName 
            : prefix + "." + child.Name.LocalName;
            
        if (child.HasElements)
        {
            foreach (var nested in FlattenXml(child, key))
            {
                result.Add(nested.Key, nested.Value);
            }
        }
        else
        {
            result.Add(key, child.Value);
        }
    }
    
    return result;
}

Example XML

xml
<Settings>
  <DatabaseServer>localhost</DatabaseServer>
  <DatabaseName>MyDB</DatabaseName>
  <Timeout>30</Timeout>
</Settings>
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.