将Dictionary(string,List <string>)序列化为xml

Grz*_*ekO 3 .net c# xml serialization

可能重复:
将Dictionary <string,string>转换为xml的简便方法,反之亦然

我有样品课:

public class SampleClass
{
   public Dictionary<string, List<string>> SampleProperties {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我想将这个类序列化为xml.我怎么能这样做?我想输出xml类似于这个例子:

<DataItem>
   <key>
      <value></value>
      <value></value>
      <value></value>
   </key>
</DataItem>
Run Code Online (Sandbox Code Playgroud)

问候

Ser*_*kiy 8

您可以使用Linq to Xml从SampleClass对象创建所需的xml:

SampleClass sample = new SampleClass();
sample.SampleProperties = new Dictionary<string, List<string>>() {
    { "Name", new List<string>() { "Greg", "Tom" } },
    { "City", new List<string>() { "London", "Warsaw" } }
};

var result = new XElement("DataItem", 
                 sample.SampleProperties.Select(kvp =>
                    new XElement(kvp.Key, 
                      kvp.Value.Select(value => new XElement("value", value)))));
result.Save(path_to_xml);
Run Code Online (Sandbox Code Playgroud)

输出:

<DataItem>
   <Name>
      <value>Greg</value>
      <value>Tom</value>
   </Name>
   <City>
      <value>London</value>
      <value>Warsaw</value>
   </City>
</DataItem>
Run Code Online (Sandbox Code Playgroud)

从xml反序列化:

SampleClass sample = new SampleClass();
sample.SampleProperties = XElement.Load(path_to_xml).Elements().ToDictionary(
                              e => e.Name.LocalName,
                              e => e.Elements().Select(v => (string)v).ToList());
Run Code Online (Sandbox Code Playgroud)