Search code examples
c#asp.netxmllinqxelement

ASP.NET convert xml string to dictionary


I have an xml doc like this:

<Tags>
  <Key>
    <Name>Model</Name>
    <Value>Raggae</Value>
  </Key>
  <Key>
    <Name>Rate</Name>
    <Value>21</Value>
  </Key>
</Tags>

I would like to create a dictionary from it that will contain as key the Name element and value the Value element.

Pls help me.

This is the code I have written I wan to know if it efficient enough:

IDictionary<string, string> XmlToDictionary(string data)
{
    XElement rootElement = XElement.Parse(data);
    var dict = new Dictionary<string, string>();
    foreach (var el in rootElement.Elements())
    {
        if (el.Name.LocalName == "Key")
        {
            foreach (var sub in el.Elements())
            {
                string key = null;
                string val = null;
                if (sub.Name.LocalName == "Name") key = sub.Value;
                if (sub.Name.LocalName == "Value") val = sub.Value;
                if (key != null && !dict.ContainsKey(key)) dict.Add(key, val);
            }
        }                
    }
    return dict;
}

Solution

  • I'm sure there is probably a more elegant solution but this would do it:

    Function

    IDictionary<string, string> XmlToDictionary(string data)
    {   
           XElement rootElement = XElement.Parse(data);
           var names = rootElement.Elements("Key").Elements("Name").Select(n => n.Value);
           var values = rootElement.Elements("Key").Elements("Value").Select(v => v.Value);
           var list = names.Zip(values, (k, v) => new { k, v }).ToDictionary(item => item.k, item => item.v);
           return list;    
    }
    

    Test

    var xmlString = @"<Tags>
      <Key>
        <Name>Model</Name>
        <Value>Raggae</Value>
      </Key>
      <Key>
        <Name>Rate</Name>
        <Value>21</Value>
      </Key>
    </Tags>";
    
    Console.WriteLine(XmlToDictionary(xmlString));