使用C#将Dictionary转换为XML

Kri*_*shh 2 asp.net dictionary linq-to-xml idictionary c#-4.0

我的XML文件如下:

<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>
Run Code Online (Sandbox Code Playgroud)

我已将此转换为以下字典,如下所示:

        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
                }));
Run Code Online (Sandbox Code Playgroud)

课程:

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

}
Run Code Online (Sandbox Code Playgroud)

我已经对我的字典进行了更改,现在我需要将其转换回XML.谁能建议我怎么做呢?

Ale*_*lex 5

你可以这样做,反之亦然:

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();
Run Code Online (Sandbox Code Playgroud)

这会让你(通过使用你的数据片段):

<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>
Run Code Online (Sandbox Code Playgroud)