3

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

我有示例课程:

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

我想将这个类序列化为 xml。我怎么能做到这一点?我想要类似于此示例的输出 xml:

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

问候

4

2 回答 2

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());
于 2013-01-13T13:46:42.520 回答
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);
}
于 2013-01-13T13:46:15.970 回答