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

时间:2013-01-13 13:39:32

标签: c# .net xml serialization

  

可能重复:
  Easy way to convert a Dictionary<string, string> to xml and visa versa

我有样班:

public class SampleClass
{
   public Dictionary<string, List<string>> SampleProperties {get;set;}
}

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

<DataItem>
   <key>
      <value></value>
      <value></value>
      <value></value>
   </key>
</DataItem>

此致

2 个答案:

答案 0 :(得分: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);

输出:

<DataItem>
   <Name>
      <value>Greg</value>
      <value>Tom</value>
   </Name>
   <City>
      <value>London</value>
      <value>Warsaw</value>
   </City>
</DataItem>

从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());

答案 1 :(得分:1)

尝试以下代码段

var dict = new Dictionary<string, List<string>>();
dict.Add("a1", new List<string>(){"a1","a2","a3"});

XElement root = new XElement("DataItem");

foreach(var item in dict)
{
  XElement element = new XElement("Key",item.Key);
  item.Value.ForEach (x => element.Add (new XElement("Value",x)));
  root.Add(element);
}