Convert Dictionary to XML using C#

Krishh picture Krishh · Jan 27, 2012 · Viewed 7.2k times · Source

I have my XML File as follows:

<states>
 <state name ="Alaska">
  <Location Name="loc1">
   <Address>testadd1</Address>
   <DateNTime>d1</DateNTime>
  </Location>
  <Location Name="loc2">
   <Address>add2</Address>
   <DateNTime>d2</DateNTime>
  </Location>
 </state>
</states>

I have converted this to the following dictionary as follows:

        XDocument doc = XDocument.Load(Server.MapPath("test2.xml"));

       IDictionary<string, Dictionary<string, Property>> dictionary = doc.Root.Elements("state").ToDictionary(
            s => s.Attribute("name").Value,
            s => s.Elements("Location").ToDictionary(
                loc => loc.Attribute("Name").Value,
                loc => new Property
                {
                    address = loc.Element("Address").Value,
                    datetime = loc.Element("DateNTime").Value
                }));

class :

public class Property
{
    public string address;
    public string datetime;

}

I have made changes to my dictionary, Now I need to convert this back to XML . Can anyone suggest me how I could go about it?

Answer

Alex picture Alex · Jan 27, 2012

You could do it vise versa:

var result = new XDocument(new XElement("states",
  dictionary.Select(i => new XElement("state", new XAttribute("name", i.Key),
      i.Value.Select(v => new XElement("Location", new XAttribute("Name", v.Key),
          new XElement("Address", v.Value.address),
          new XElement("DateNTime", v.Value.datetime)
      ))
  ))
));

var xml = result.ToString();

This gets you (by using your data fragment):

<states>
  <state name="Alaska">
    <Location Name="loc1">
      <Address>testadd1</Address>
      <DateNTime>d1</DateNTime>
    </Location>
    <Location Name="loc2">
      <Address>add2</Address>
      <DateNTime>d2</DateNTime>
    </Location>
  </state>
</states>